[英]Faster/smarter loops [Python]
数据文件是一个包含4列的Excel列表:名称,位置,值和价格。 用熊猫导入的文件。
有5个不同的职位。
我正在尝试匹配所有不同的可能性,其中每个位置只能是一个+尚未选择的一个随机玩家。
def teams(x):
positions = list(data.Position.unique())
indices = []
for position in positions:
indices.append((data.Position == position).nonzero()[0])
positions.append('Random')
indices.append(data.index)
for i in indices[0]:
for i2 in indices[1]:
for i3 in indices[2]:
for i4 in indices[3]:
for i5 in indices[4]:
for i6 in indices[5]:
if i6 != i:
if i6 != i2:
if i6 != i3:
if i6 != i4:
if i6 != i5:
print i, i2, i3, i4, i5, i6
teams(data)
我的问题是我的循环太慢,无法使用if
语句,因此我必须使5个不同的if
s成为可能,这是一个非常愚蠢的解决方案。
我的问题是:如何使循环更快/更智能,以及如何修复if
语句
如果像这样使用itertools.product()
则可以将代码缩短为三行
from itertools import product
for i in list(product(*indices)):
if i[5] not in i[:5]:
print i[0], i[1], i[2], i[3], i[4], i[5]
product()
等效于嵌套的for循环
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.