在python中构建不同的对

2024-09-27 07:32:40 发布

您现在位置:Python中文网/ 问答频道 /正文

productcode = ['apple','orange','melons'] # 1000+ more
pairs = []
count = 0
for xi,x in enumerate(productcode):
    del productcode[xi]
    for yi,y in enumerate(productcode):
        pc2 += 1
        p = (x,y)
        pairs.append(p)

print ("Number of distinct pairs:",pc2)

productcode包含一千多个数据项:

^{pr2}$

预期产量:

apple orange

apple grape

orange grape

嵌套的for循环只迭代列表(productcode)中一半的项,因此我得到的对数比我预期的要少得多。有谁能帮我解释一下我做错了什么,或者实际发生了什么?在


Tags: inappleformorecountdelorangepairs
2条回答

在迭代集合的同时修改它。坏主意。在

这是cool datastructure that gets rid of duplicates

创建大量重复数据:

from itertools import combinations

# make all 2-length combinations of 1,2,3,1,2,3,4,5,3   
comb = list(combinations([ 1,2,3,1,2,3,4,5,3  ],2)) # works with strings as well
print(comb) 

输出:

^{pr2}$

使数据唯一:

uniques = set(comb)
print(uniques)  

输出:

^{4}$

如果您需要某个东西的所有combinations,请事先将somethings填充到set中,以删除所有重复,并通过set创建您的combinations。如果您在一个list上使用combinations,那么您将创建不需要的多个combinations-因此set,然后从中生成combinations。在


set(和dict)的缺点是它们需要不可变的键,因此tuples很好,lists不是,但是{}工作得很好。如果需要,您可以tuple(alist)。在

^{}是很自然的选择。为了避免重复,只需先将list转换为set。根据您是否需要有序的结果,有两种类似的解决方案。在

已订购

from itertools import combinations

productcode = ['apple', 'orange', 'grape']

res_lst = sorted(map(sorted, combinations(set(productcode), 2)))

# [['apple', 'grape'], ['apple', 'orange'], ['grape', 'orange']]

我不知道你需要什么顺序,所以我把内的子列表按字母顺序排序。在

无序

如果顺序在任何地方都不重要,那么您需要使用set项的frozenset项:

^{pr2}$

这是因为set项必须是不可变的;frozenset是{}的不可变版本。这是一对自然的考验。例如:

{'orange', 'apple'} in res_set  # True

另一种方法是使用一组按字母顺序排序的元组。在

相关问题 更多 >

    热门问题