如何创建预期列表?

2024-10-16 17:18:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面3个清单。我想创建一个预期的_列表,该列表与列表1具有相同的形状,如果列表1中的元素具有“Review at”,则它将包含列表2中的元素,否则它将为空(“”)

list1 = [  "Review abcd"
           "Neu"
           "Review defg"
           "Review hmk"
           "hmd"
           "Review lmi"
           "Review yuj"
           "jmf"
           "Review  Bad"]

list2 = [ "http1"
          "http2"
          "http3"
          "http4"
          "http5"
          "http6"]

expected_list = [ "http1"
                  ""
                  "http2"
                  "http3"
                  ""
                  "http4"
                  "http5"
                  ""
                  "http6"]    

我尝试了以下代码

for idx, item in enumerate(list1): 
    if "Review" in list1[idx]:
        for j in rang(len(list2))
            expected_list.append(list2[j])
    else:
        expected_list.append("")

但是,在满足条件的每个元素中,它都会附加list2中的所有元素。因此,预期列表的形状比预期的更多。我知道创建第二个循环是错误的。但是我怎样才能修复它呢


Tags: in元素列表reviewlist形状expectedlist2
2条回答

这些列表是一个元素,需要用逗号分隔值:

need commas

此外,你不需要很多东西:

j = 0
for each in list1: 
    if "Review" in each:
        expected_list.append(list2[j])
    else:
        expected_list.append("")
    j+=1

你只需要像这样的东西:

for idx, item in enumerate(list1): 
    if "Review" in item: # use *item* here, that's the whole point of enumerate
        expected_list.append(list2[idx])
    else:
        expected_list.append("")

更好的方法是使用zip

for item1, item2 in zip(list1, list2):
    if "Review" in item1:
        expected_list.append(item2)
    else:
        expected_list.append("")

相关问题 更多 >