gpt4 book ai didi

python - 更快/更智能的循环 [Python]

转载 作者:行者123 更新时间:2023-11-28 21:11:20 25 4
gpt4 key购买 nike

数据文件是一个包含 4 列的 Excel 列表:名称、位置、值(value)和价格。使用 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)

我的问题是我的循环太慢了,我无法让 if 语句工作所以我必须制作 5 个不同的 if,我假设是一个非常愚蠢的解决方案。

我的问题是:我怎样才能让我的循环更快/更聪明,我该如何修复我的 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 循环

关于python - 更快/更智能的循环 [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35512936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com