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)中一半的项,因此我得到的对数比我预期的要少得多。有谁能帮我解释一下我做错了什么,或者实际发生了什么?在
在迭代集合的同时修改它。坏主意。在
这是cool datastructure that gets rid of duplicates:
创建大量重复数据:
输出:
^{pr2}$使数据唯一:
输出:
^{4}$如果您需要某个东西的所有combinations,请事先将somethings填充到
set
中,以删除所有重复,并通过set
创建您的combinations
。如果您在一个list
上使用combinations
,那么您将创建不需要的多个combinations
-因此set
,然后从中生成combination
s。在set(和dict)的缺点是它们需要不可变的键,因此}工作得很好。如果需要,您可以
tuples
很好,lists
不是,但是{tuple(alist)
。在^{} 是很自然的选择。为了避免重复,只需先将
list
转换为set
。根据您是否需要有序的结果,有两种类似的解决方案。在已订购
我不知道你需要什么顺序,所以我把内的和跨子列表按字母顺序排序。在
无序
如果顺序在任何地方都不重要,那么您需要使用
^{pr2}$set
项的frozenset
项:这是因为}的不可变版本。这是一对自然的考验。例如:
set
项必须是不可变的;frozenset
是{另一种方法是使用一组按字母顺序排序的元组。在
相关问题 更多 >
编程相关推荐