[英]Comparing nested list Python
I guess the code will most easily explain what I'm going for... 我想代码最容易解释我的目的...
list1 = [("1", "Item 1"), ("2", "Item 2"), ("3", "Item 3"), ("4", "Item 4")]
list2 = [("1", "Item 1"), ("2", "Item 2"), ("4", "Item 4")]
newlist = []
for i,j in list1:
if i not in list2[0]:
entry = (i,j)
newlist.append(entry)
print(newlist)
if we call the nested tuples [i][j] 如果我们调用嵌套元组[i] [j]
I want to compare the [i] but once this has been done I want to keep the corresponding [j] value. 我想比较[i]但是一旦完成,我想保留相应的[j]值。
I have found lots of information regarding nested tuples on the internet but most refer to finding a specific item. 我在互联网上找到了很多关于嵌套元组的信息,但大多数都是找到一个特定的项目。
I did recently use an expression below, which worked perfectly, this seems very similar, but it just won't play ball. 我最近使用了一个下面的表达式,它完美地工作,这看起来很相似,但它只是不会打球。
for i,j in highscores:
print("\tPlayer:\t", j, "\tScore: ", i)
Any help would be much apppreciated. 任何帮助都会得到很多应用。
If I understand correctly from your comment you would like to take as newlist: 如果我从您的评论中理解正确,您可以将其作为新列表:
newlist = [("3", "Item 3")]
You can do this using: 你可以这样做:
1) list comprehension: 1)列表理解:
newlist = [item for item in list1 if item not in list2]
print newlist
This will give you as a result: 这会给你一个结果:
[('3', 'Item 3')]
2) You could also use symmetric difference like: 2)你也可以使用对称差异,如:
L = set(list1).symmetric_difference(list2)
newlist = list(L)
print newlist
This will also give you the same result! 这也会给你相同的结果!
3) Finally you can use a lambda function like: 3)最后你可以使用lambda函数,如:
unique = lambda l1, l2: set(l1).difference(l2)
x = unique(list1, list2)
newlist = list(x)
This will also produce the same result! 这也会产生相同的结果!
4) Oh, and last but not least, using simple set properties: 4)哦,最后但并非最不重要的是,使用简单的设置属性:
newlist = list((set(list1)-set(list2)))
I think you just want to create a set of the first elements of list2, if you're only looking to compare the first element of the lists. 我想你只想创建一组list2的第一个元素,如果你只想比较列表的第一个元素。
newlist = []
list2_keys = set(elem[0] for elem in list2)
for entry in list1:
if entry[0] not in list2_keys:
newlist.append(entry)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.