[英]Comparing two lists and making new list
So lets say I have two lists a=[1,2,3,4,5,6]
and b=[2,34,5,67,5,6]
I want to create a third list which will have 1
where elements are different in a
and b
and 0
when they are same, so above would be like c=[1,1,1,1,0,0]
所以假设我有两个列表
a=[1,2,3,4,5,6]
和b=[2,34,5,67,5,6]
我想创建第三个列表,其中有1
元素在a
和b
和0
相同时是不同的,所以上面就像c=[1,1,1,1,0,0]
You can zip the lists and compare them in a list comprehension.您可以 zip 列表并在列表理解中比较它们。 This takes advantage of the fact that booleans are equivalent to 1 and 0 in python:
这利用了布尔值相当于 python 中的 1 和 0 的事实:
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
[int(m!=n) for m, n, in zip(a, b)]
# [1, 1, 1, 1, 0, 0]
Try a list comprehension over elements of each pair of items in the list with zip
:尝试使用
zip
对列表中每对项目的元素进行列表理解:
[ 0 if i == j else 1 for i,j in zip(a,b) ]
Iterating with a for loop is an option, though list comprehension may be more efficient.使用 for 循环进行迭代是一种选择,尽管列表理解可能更有效。
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
c=[]
for i in range(len(a)):
if a[i] == b[i]:
c.append(0)
else:
c.append(1)
print(c)
prints印刷
[1, 1, 1, 1, 0, 0]
If you will have multiple vector operations and they should be fast.如果您将有多个向量操作并且它们应该很快。 Checkout
numpy
.结帐
numpy
。
import numpy as np
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
a = np.array(a)
b = np.array(b)
c = (a != b).astype(int)
# array([1, 1, 1, 1, 0, 0])
idk if this is exactly what youre loocking for but this should work:如果这正是您正在寻找的东西,那么这应该可行:
edidt: just found out that Joe Thor commented almost the exact same a few minutes earlier than me lmao edidt:刚刚发现 Joe Thor 比我早几分钟发表了几乎完全相同的评论 lmao
a = [1, 2, 3, 4, 5, 6]
b = [2, 34, 5, 67, 5, 6]
results = []
for f in range(0, len(a)):
if a[f] == b[f]:
results.append(0)
else:
results.append(1)
print(results)
This can be done fairly simply using a for loop.这可以使用 for 循环相当简单地完成。 It does assume that both lists, a and b, are the same length.
它确实假设两个列表 a 和 b 的长度相同。 An example code would like something like this:
示例代码如下所示:
a = [1,2,3,4,5,6]
b = [2,34,5,67,5,6]
c = []
if len(a) == len(b):
for i in range(0,len(a)):
if(a[i] != b[i]):
c.append(1)
else:
c.append(0)
This can also be done using list comprehension:这也可以使用列表推导来完成:
a = [1,2,3,4,5,6]
b = [2,34,5,67,5,6]
c = []
if len(a) == len(b):
c = [int(i != j) for i,j in zip(a,b)]
The list comprehension code is from this thread: Comparing values in two lists in Python列表理解代码来自此线程: Comparing values in two lists in Python
a = [1, 2, 3, 4, 5, 6]
b = [2, 34, 5, 67, 5,6]
c = []
index = 0
x = 1
y = 0
for i in range(len(a)): # iterating loop from index 0 till the last
if a[index]!= b[index]: # comapring each index
c.append(x) # if not equal append c with '1'
index += 1 # increment index to move to next index in both lists
else:
c.append(y)
index += 1
print(c)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.