python - 如何创建所有可能的唯一列表

标签 python loops python-2.7 unique

我正在为我的篮球队编写一个短程序。我已经让教练将球员分成与特定位置相对应的列表。 (List1 = 控球后卫)

使用这些列表,我想创建一个包含所有可能的“有效”阵容的输出。

目前,我已经编写了一个从每个列表中选择 5 个不同的人的基本程序

我怎样才能让它以打印出 5 个玩家的所有“有效”配置的方式循环?

非常感谢任何建议或方向!

这是我目前所拥有的:

import sys
import random    

list1 = ['Gabe', 'taylor', 'kyle', 'jay']
list2 = ['Gabe', 'Taylor', 'Kyle', 'Jay', 'James', 'John', 'Tyde','Chris', 'Bruno', 'David']
list3 = ['Gabe', 'Taylor', 'Kyle', 'Jay', 'James', 'John', 'Tyde','Chris', 'Bruno', 'David']
list4 = ['Kyle', 'James', 'John', 'Tyde','Bruno', 'Drew', 'Chris']
list5 = ['James', 'John', 'Brendan','Tim', 'Drew' ]
FinalList = []


position_lists = [list1, list2, list3, list4, list5]

for position_list in position_lists: # for every position

    found_my_guy = False

    while not found_my_guy: # keep looping till I find my guy

        selectedPerson = position_list[ random.randint( 0,len(position_list) -1 ) ]

        if selectedPerson not in FinalList: # only append guys that are not duplicates
            FinalList.append(selectedPerson)
            found_my_guy = True # exit while loop and go to next `lineup'


for person in FinalList:
    sys.stdout.write(person + '\n')

最佳答案

我们可以使用itertools.product生成列表的笛卡尔积,然后过滤掉所有重复的结果:

from itertools import product

list1 = ['Gabe', 'Taylor', 'Kyle', 'Jay']
list2 = ['Gabe', 'Taylor', 'Kyle', 'Jay', 'James', 'John', 'Tyde','Chris', 'Bruno', 'David']
list3 = ['Gabe', 'Taylor', 'Kyle', 'Jay', 'James', 'John', 'Tyde','Chris', 'Bruno', 'David']
list4 = ['Kyle', 'James', 'John', 'Tyde','Bruno', 'Drew', 'Chris']
list5 = ['James', 'John', 'Brendan','Tim', 'Drew' ]

FinalList = []

for x in product(list1, list2, list3, list4, list5):
    # check for duplicates
    if len(set(x)) == 5 and set(x) not in FinalList:
        FinalList.append(set(x))


# to print
for x in FinalList:
    print x

我相信有更有效的方法来计算这样的列表,但这段代码基本上可以立即在我的笔记本电脑上运行。

此外,要解决您的第二个问题,基本上您的做法是错误的。从理论上讲,随机猜测可以让您创建所有可能的名称集,但您只能接近无穷大。在实践中,这当然会更快,但仍然比直接生成列表效率低得多。

编辑:另外,作为最后的说明:

>>> len(FinalList)
970

(此列表可能没有真正的帮助...)

关于python - 如何创建所有可能的唯一列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20233370/

相关文章:

macos - numpy 未安装在 macOS 上

python - 如何使用反射或解析读取Python类中声明成员的顺序(禁止元类替换)?

python - 为什么 string > int 的计算结果为 True?

python - 动态全局变量赋值

python - Django 身份验证不返回任何内容

python - 在 Python 中的文本文件中间插入一行

c - 在 C 中循环使 RScript 性能更高效

python - 如何排列元组列表,以便删除与其他元组相比具有最高值的元组并返回最大值

java - 如何在java中迭代字符串数组的一列

arrays - 有没有办法在用户输入特定数字之前创建数组?