如何比较列表中对应位置的元素?
我有N个长度相同的列表。我该如何比较这些列表中对应的位置,并输出它们完全匹配的位置数量呢?
举个例子:
A=[1,0,1,1]
B=[1,1,1,1]
C=[1,0,1,0]
比较这三个列表,结果会输出2
,因为只有位置1和位置3是匹配的。
我在想把它们转换成元组,然后用K=zip(A,B,C)
把它们合并在一起,再逐个检查每个元组,看它们是否都相等。
这个问题听起来好像我遗漏了什么很简单的东西,也许吧!
4 个回答
0
如果你想知道所有列表匹配的位置,可以使用下面的代码:
list(x for x, (xa, xb, xc) in enumerate(zip(a, b, c))
if xa == xb == xc)
我觉得这个方法是最容易理解的。
如果你只是想统计列的数量,可以用下面的代码:
sum(xa == xb == xc for xa, xb, xc in zip(a, b, c))
这个方法之所以有效,是因为在Python中,True
和False
可以像数字1
和0
一样用于计算。
1
使用 set
,就像gnibbler的回答中提到的那样,可以处理包含任何类型的不可变元素的列表,比如任意的整数、浮点数、字符串和元组。提问者的问题没有限制列表中可以包含什么内容,假设只有0和1并没有简化问题。以下的代码也适用于任意数量的列表,而不仅仅是3个,这似乎也是提问者的要求之一。
A=[1,0,1,1, 'cat', 4.5, 'no']
B=[1,1,1,1, 'cat', False, 'no']
C=[1,0,1,0, 16, 'John', 'no']
D=[1,0,0,0, (4,3), 'Sally', 'no']
def number_of_matching_positions(*lists):
"""
Given lists, a list of lists whose members are all of the same length,
return the number of positions where all items in member lists are equal.
"""
return sum([len(set(t)) <= 1 for t in zip(* lists)])
print(number_of_matching_positions(),
number_of_matching_positions(A),
number_of_matching_positions(A, A),
number_of_matching_positions(A, B),
number_of_matching_positions(A, B, C),
number_of_matching_positions(A, B, C, D))
这段代码会输出 0 7 7 5 3 2
。
如果列表的数量 N
可能很大,可以通过尽量少检查每个元组中的元素来提高性能:
def all_equal(t):
"""Return True if all elements of the sequence t are equal, False otherwise."""
# Use a generator comprehension,
# so that 'all' will stop checking t[i] == t[0]
# as soon as it's false for some i.
return (not t) or \
all( (t[i] == t[0] for i in range(1, len(t))) )
def number_of_matching_positions_alt(*lists):
# Instead of 'len(set(t)) <= 1',
# do less work in case len(lists) alias len(t) can be large
return sum( [all_equal(t) for t in zip(* lists)] )
4
这段代码的意思是……
首先,它定义了一些变量,这些变量可以用来存储数据。接着,它可能会进行一些操作,比如计算或者比较这些数据。最后,代码会输出结果,可能是显示在屏幕上,或者保存到文件里。
总的来说,这段代码的主要目的是处理一些信息,并给出一个结果。你可以把它想象成一个小工具,它接收输入,进行处理,然后给你想要的答案。
如果你对代码的某个部分有疑问,可以逐行分析,看看每一行在做什么,这样会更容易理解。
sum(1 if x == y == z else 0 for x, y, z in zip(A, B, C))
2
6
>>> A = [1, 0, 1, 1]
>>> B = [1, 1, 1, 1]
>>> C = [1, 0, 1, 0]
>>> [len(set(i)) == 1 for i in zip(A,B,C)]
[True, False, True, False]
>>> sum(len(set(i))==1 for i in zip(A,B,C))
2
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。