Sve*_*lic 2 python performance loops nested-loops
数据文件是一个包含4列的Excel列表:名称,位置,值和价格.用pandas导入的文件.
有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)
Run Code Online (Sandbox Code Playgroud)
我的问题是我的循环太慢而且我无法使if语句工作所以我必须制作5个不同的ifs,我认为这是一个非常愚蠢的解决方案.
我的问题是:如何让我的循环更快/更智能,以及如何修复我的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]
Run Code Online (Sandbox Code Playgroud)
product() 相当于嵌套for循环