将元素添加到嵌套lis的pythonic方法

2024-09-27 18:02:13 发布

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

我有一张名单:

listSchedule = [[list1], [list2], etc..]]

我有另一个列表,如果每个嵌套列表的第一个元素与字符串匹配,我想将该列表的元素附加到每个嵌套列表中。你知道吗

我可以做到,但我想知道是否有一个更'Python'的方式,使用列表理解?你知道吗

index = 0;
for row in listSchedule:
   if row[0] == 'Download':
      row[3] = myOtherList[index]
      index +=1

Tags: 字符串in元素列表forindexifdownload
3条回答

你的代码可读性很强,我不会更改它。你知道吗

通过列表理解,你可以写下如下内容:

for index, row in enumerate([row for row in listSchedule if row[0] == 'Download']):
    row[3] = myOtherList[index]

您可以尝试一下,但要复制一份otherlist,以免丢失信息:

[row+[myotherlist.pop(0)] if row[0]=='Download' else row for row in listScheduel]

例如:

list = [['Download',1,2,3],[0,1,2,3],['Download',1,2,3],['Download',1,2,3]]
otherlist = [0,1,2,3,4]
l = [ row+[otherlist.pop(0)] if row[0]=='Download' else row for row in list]

输出:

[['Download', 1, 2, 3, 0],
[0, 1, 2, 3],
['Download', 1, 2, 3, 1],
['Download', 1, 2, 3, 2]]

如果你真的想append,为什么不使用row.append(myOtherList[index])?这样你就避免了IndexErrors

i = 0

for row in listSchedule:
    if row[0]=="Download":
        row.append(myOtherList[i])
        i+=1

相关问题 更多 >

    热门问题