我有一个列表 L 并想从中随机返回 n 个项目的列表。
现在我依赖 itertools.combinations,然后随机选择一个,但我必须等待一段时间,直到列表看起来没有在列表开头附近粘有很多项目,所以它并不是真的“随机的。”
假设我有两个可迭代对象,一个是有限的,一个是无限的:
import itertools
teams = ['A', 'B', 'C']
steps = itertools.count(0, 100)
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以避免嵌套的 for 循环并使用itertools模块中的无限迭代器之一,例如cycle或repeat来获取这些迭代器的笛卡尔积。
循环应该是无限的,因为 的停止值steps预先未知。
预期输出:
$ python3 test.py
A 0
B 0
C 0
A 100
B 100
C 100
A 200
B 200
C 200
etc...
Run Code Online (Sandbox Code Playgroud)
带有嵌套循环的工作代码:
from itertools import count, cycle, repeat
STEP = 100
LIMIT = 500
TEAMS = ['A', 'B', 'C']
def test01():
for step in count(0, STEP):
for team in TEAMS:
print(team, step)
if …Run Code Online (Sandbox Code Playgroud) 我通常会写:
for i in range(len(collection)):
for j in range(i + 1, len(collection)):
print(collection[i], collection[j])
Run Code Online (Sandbox Code Playgroud)
这取决于所订购的元素。使用无序集合时如何做到这一点?
我有一个清单[1,2,3].我想要一个接收列表的函数和另一个数字,即长度.
f([1, 2, 3], 4) = [
[1, 1, 1, 1],
[1, 1 , 1, 2],
[1, 1, 1, 3],
[1, 1, 2, 1],
[1, 1, 3, 1],
#and so on...
]
Run Code Online (Sandbox Code Playgroud)
也许itertools有答案?
我对python3.6中的内存错误有一些疑问
import itertools
input_list = ['a','b','c','d']
group_to_find = list(itertools.product(input_list,input_list))
a = []
for i in range(len(group_to_find)):
if group_to_find[i] not in a:
a.append(group_to_find[i])
Run Code Online (Sandbox Code Playgroud)
group_to_find = list(itertools.product(input_list,input_list))
MemoryError
Run Code Online (Sandbox Code Playgroud)