Python 如何创建预期列表?
我有下面3个清单。我想创建一个预期的_列表,该列表与列表1具有相同的形状,如果列表1中的元素具有“Review at”,则它将包含列表2中的元素,否则它将为空(“”) 我尝试了以下代码Python 如何创建预期列表?,python,list,Python,List,我有下面3个清单。我想创建一个预期的_列表,该列表与列表1具有相同的形状,如果列表1中的元素具有“Review at”,则它将包含列表2中的元素,否则它将为空(“”) 我尝试了以下代码 for idx, item in enumerate(list1): if "Review" in list1[idx]: for j in rang(len(list2)) expected_list.append(list2[j])
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中的所有元素。因此,预期列表的形状比预期的更多。我知道创建第二个循环是错误的。但是我怎样才能修复它呢?您只需要像这样的东西:
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("")
你只需要像这样的东西:
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("")
这些列表是一个元素,需要用逗号分隔值: 此外,你不需要很多东西:
j = 0
for each in list1:
if "Review" in each:
expected_list.append(list2[j])
else:
expected_list.append("")
j+=1
这些列表是一个元素,需要用逗号分隔值: 此外,你不需要很多东西:
j = 0
for each in list1:
if "Review" in each:
expected_list.append(list2[j])
else:
expected_list.append("")
j+=1
需要逗号分隔值您尝试过调试代码不工作的原因吗?需要逗号分隔值您尝试过调试代码不工作的原因吗?谢谢。在我的例子中,我应该把j+=1放在expected_list.append(list2[j])行下,因为如果每次评审中都没有评审,我不希望list2的索引增加。顺便说一句,谢谢你为我点亮了一盏灯。谢谢你。在我的例子中,我应该把j+=1放在expected_list.append(list2[j])行下,因为如果每次评审中都没有评审,我不希望list2的索引增加。顺便说一句,谢谢你为我点亮了一盏灯。