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

时间:2018-09-20 13:13:52

标签: python

我有一个嵌套列表:

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

我还有另一个列表,如果每个列表的第一个元素与字符串匹配,我想将此列表的元素追加到每个嵌套列表中。

我可以做到,但是我想知道使用列表理解是否还有更多的“ pythonic”方式?

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

4 个答案:

答案 0 :(得分:4)

您的代码可读性强,我不会更改它。

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

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

答案 1 :(得分:1)

您可以尝试这样做,但要复制另一个列表,以免丢失信息:

[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]]

答案 2 :(得分:0)

如果您想真正地LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_DESTROY: PostQuitMessage(0); return 0; case WM_PAINT: PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1)); EndPaint(hwnd, &ps); return 0; } return DefWindowProc(hwnd, uMsg, wParam, lParam); } ,为什么不使用append?这样一来,您就避免了row.append(myOtherList[index])

IndexErrors

答案 3 :(得分:0)

我们可以使用队列,并在满足条件时逐一弹出其值。为了避免数据复制,我们使用迭代器将队列实现为myOtherList上的视图(感谢ShadowRanger)。

queue = iter(myOtherList)

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