【问题标题】:Create new list by comparing first row item in first list to items in second list通过将第一个列表中的第一行项目与第二个列表中的项目进行比较来创建新列表
【发布时间】:2017-12-29 07:20:45
【问题描述】:

我是 python 新手,来自 Matlab,我仍在适应使用列表而不是数组。我有两个列表,如果每行中的项目与第二个中的任何元素匹配,我正在尝试使用第一个中的项目创建第三个。基本上,我有

list1 = [['name1',height1,length1],['name2',height2,length2]...['name9',height9,length9]
list2 = ['name1','name9']
list3 = []

想要类似的东西

for row in list1
    if first element (namex) in row is in list2
        append row to list 3

我想要一个 list3,其中包含 list1 的第一个项目与 list2 中的项目匹配的行。

list3 = [['name1',height1,lenght1],['name9',height9,length9]]

我尝试了两种不同的方法,但都导致一个空白列表3:

list3 = [item for item in list1 if item[0] in list2]

for rows in list1:
    if list1[0] in list2:
        list3.append(rows)

知道列表不能像数组一样被索引,我怎样才能在这里获得类似的功能?

【问题讨论】:

  • 你想要的输出是什么?
  • 那么您发布的代码有什么问题?列表推导会产生您预期的输出,不是吗?
  • @Rawing 列表三执行代码后显示为空
  • 嗯,不,不,它没有。可以发minimal reproducible example吗?
  • @Rawing 嗯,我的代码在创建列表之前一定有问题吗?我会看看。感谢您确认方法!

标签: python list compare


【解决方案1】:

您提出的第一个方法对我来说效果很好。

要使第二种方法起作用,需要将其编辑如下:

list3 = []
for row in list1:
    if row[0] in list2:
        list3.append(row)

【讨论】:

    【解决方案2】:

    if 检查应该使用rows[0] 而不是list1[0]

    for row in list1:
        if row[0] in list2:
            list3.append(rows)
    

    这可以浓缩成一个列表推导式。

    list3 = [row for row in list1 if row[0] in list2]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多