简体   繁体   English

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

[英]pythonic way to add elements to nested list

I have a nest list: 我有一个嵌套列表:

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

I have another list and I want to append to each nested list the element of this list if the first element of each matches a string. 我有另一个列表,如果每个列表的第一个元素与字符串匹配,我想将此列表的元素追加到每个嵌套列表。

I can do it but I wonder if there is a more 'pythonic' way, using list comprehension? 我可以做到,但我想知道使用列表理解是否还有更多的“ pythonic”方式?

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

Your code is very readable, I would not change it. 您的代码可读性强,我不会更改。

With a list comprehension you could write something like: 通过列表理解,您可以编写如下内容:

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

you could try that but make a copy of the otherlist to not lose the info: 您可以尝试这样做,但要复制另一个列表,以免丢失信息:

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

for example: 例如:

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]

Output: 输出:

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

If you want to truly append , why not use row.append(myOtherList[index]) ? 如果要真正append ,为什么不使用row.append(myOtherList[index]) That way you avoid IndexErrors 这样就避免了IndexErrors

i = 0

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

We can use a queue and pop its values one by one when we meet the condition. 满足条件后,我们可以使用队列并逐个弹出其值。 To avoid copying of data let's implement the queue as a view over myOtherList using an iterator (thanks to ShadowRanger ). 为了避免复制数据,让我们使用迭代器将队列实现为myOtherList的视图(感谢ShadowRanger )。

queue = iter(myOtherList)

for row in listSchedule:
    if row[0] == "Download":
        row.append(next(iter))

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

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