简体   繁体   English

比较列表列表并将某些元素写入新列表

[英]Comparing lists of lists and writing certain elements into a new list

It looks like this question has been asked dozens of times, but none of the answers have helped me out, so I'm afraid I'm asking it again (please don't hate me!). 看来这个问题已经被问过几十遍了,但是没有一个答案能帮助我,所以恐怕我又要问了(请不要讨厌我!)。 I have two lists of lists: 我有两个列表列表:

amm = [['0005FC66DF', '4403'", ',\n'], [" ['0001C52E02', '4406'", ',\n'],etc] 

and

data = [['07/11/2012', '09:53:36', 'Thing', '#0F', '0006E7895B', 'T', 'U\n'], ['05/13/2012', '09:54:27', 'Thing', '#0F', '0006E3DADA', 'T', 'U\n'], etc]. 

I want to see if the 5th element in a list in data is the same as the first element in a list in amm, and if so, I want to write the list from data to a new list of lists, amv. 我想查看数据列表中的第5个元素是否与amm中列表中的第一个元素相同,如果是,我想将数据中的列表写到新的列表amv中。 I have tried EVERYTHING. 我尝试了一切。 I started with 我开始

for i in data:
  if data[i][4] in amm:
    amv[i].append(i)

which didn't write anything to amv, so I tried 没有写任何东西给amv,所以我尝试了

amv=[item for item in data if item[4] in[items for items in amm]]

which had the same problem, so I tried 有同样的问题,所以我尝试了

   for i in data:
    for j in amm:
        if i[4] == j[0]:
             amv.append(j)

and a million (probably slightly more accurate) variations on these themes. 以及这些主题的上百万种变化(可能略微准确)。 This should be such a simple thing to do but it's just not working for me. 这应该是一件很简单的事情,但是对我来说不起作用。 Any help would be very, very much appreciated. 任何帮助将非常非常感谢。 Thanks in advance! 提前致谢!

EDIT Sorry this wasn't very clear. 编辑抱歉,目前还不清楚。 What I'm trying to do is write a new list (amv) that contains all the lists in data that have their fifth element appear in amm. 我想做的是编写一个新列表(amv),其中包含数据中的所有列表,这些列表的第五个元素出现在amm中。 All of the scripts I've shown haven't added anything to the new list, amv. 我展示的所有脚本都没有将任何内容添加到新列表amv中。 amv has always stayed empty, and I can't figure out why.. amv总是空着,我不知道为什么。

s = set(x[0] for x in amm)
amv = [x for x in data if x[4] in s]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM