【问题标题】:Faster/smarter loops [Python]更快/更智能的循环 [Python]
【发布时间】:2016-06-01 11:26:21
【问题描述】:

数据文件是一个 Excel 列表,有 4 列:名称、位置、价值和价格。使用 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 个不同的 ifs,我认为这是一个非常愚蠢的解决方案。

我的问题是:如何让我的循环更快/更智能,以及如何修复我的 if 语句

【问题讨论】:

  • 你可以为你的 if 语句做if i6 not in [i,i2,i3,i4,i5]
  • 每个索引有多少个元素?
  • atm 大约有 10 个,预计最后一个大约有 50 个

标签: python performance loops nested-loops


【解决方案1】:

如果你像这样使用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 循环

【讨论】:

  • 这段代码确实更短,但仍然很慢。有没有办法让它更快?
  • @Svelic 我想不出任何其他方法。如果每个索引有 10 个元素,最后一个有 50 个元素,那么您将看到 500 万种可能性。缓存可能是一种选择,但我不知道如何将其应用于此问题。对不起
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-15
  • 2016-05-21
  • 2019-12-25
  • 1970-01-01
相关资源
最近更新 更多