![](/img/trans.png)
[英]Python: Compare first n characters of item in list to first n characters of all other items in same list
[英]how to compare one item in a list with all the other items in this list, python
我有一个这样的列表:
all = [[a,b,c,d],[r,d,g,s],[e,r,a,b],[p,o,i,u]....(more similar items)]
我想知道它们中有多少项是相同的,所以我需要将all[0]
与all[1],all[2]...all[(len(all)-1)]
,然后使用all[1]
与all[2],all[3]...all[(len(all)-1)]
all[1]
进行比较all[2],all[3]...all[(len(all)-1)]
,然后all[2]
与all[3],all[4],...all[(len(all)-1)]
进行比较all[3],all[4],...all[(len(all)-1)]
我试过这样的事情:
for i in range(len(all)):
print len(all[i] & all[i+1]) ##how many identical items shared by all[0] and all[1]
print len(all[i+1] & all[i+2])
但不知道如何继续,我想得到的结果是:
item1 has 3 same values with item2,
has 4 same values with item3,
has 1 same values with item4....
item2 has 3 same values with item1,
has 2 same values with item3,
etc
这里最简单的算法是^ 2。 只需在列表上循环两次:
for x, left in enumerate(all):
for y, right in enumerate(all):
common = len(set(left) & set(right))
print "item%s has %s values in common with item%s"%(x, common, y)
套装是要走的路。 。 。
all = [[1,2,3,4],[1,2,5,6],[4,5,7,8],[1,8,3,4]]
set_all = [set(i) for i in all]
for i in range(len(all)):
for j in range(len(all)):
if i == j:
continue
ncom = len(set_all[i].intersection(set_all[j]))
print "List set %s has %s elements in common with set %s" % (i, ncom, j)
List set 0 has 2 elements in common with set 1 List set 0 has 1 elements in common with set 2 List set 0 has 3 elements in common with set 3 List set 1 has 2 elements in common with set 0 List set 1 has 1 elements in common with set 2 List set 1 has 1 elements in common with set 3 List set 2 has 1 elements in common with set 0 List set 2 has 1 elements in common with set 1 List set 2 has 2 elements in common with set 3 List set 3 has 3 elements in common with set 0 List set 3 has 1 elements in common with set 1 List set 3 has 2 elements in common with set 2
基本上你要做的是计算每个列表中元素集与每个其他列表的交点长度。 尝试这个:
a = [['a','b','c','d'],['r','d','g','s'],['e','r','a','b'],['p','o','i','u']]
for i in range(len(a)):
for j in range(len(a)):
print "item%d has %d same values as item%d" % ( i, len(set(a[i]) & set(a[j])) ,j )
输出格式并不完全符合您的要求,但您明白了。
如果你正在寻找最短的答案,因为你是一个像我这样懒惰的人!
>>> my_list = [['a','b','c','d'],['r','d','g','s'],['e','r','a','b'],['p','o','i','u']]
>>> for i, sub_list in enumerate(my_list):
... print 'item %d shares with %r'%(i, map(lambda a, b: len(set(a) & set(b)), sub_list, my_list))
...
item 0 shares with [1, 0, 0, 0]
item 1 shares with [0, 1, 0, 0]
item 2 shares with [0, 1, 1, 0]
item 3 shares with [0, 0, 0, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.