如何通过其他两个列表的组合创建每个元素(列表)的2D列表?

时间:2018-12-09 10:58:29

标签: python python-3.x list nested-lists

我有两个列表:

D1=[["a "," "," "," "," "," "],["b "," ","o"," "," "," "],["c ","x"," "," "," "," "],["d "," "," "," "," "," "],["e "," "," "," "," "," "]]

D2=[["a "," ","o"," ","x"," "],
["b "," "," "," "," "," "],["c "," "," "," "," "," "],["d "," "," "," "," "," "],["e "," "," "," "," "," "]]

D=[]

我想创建一个列表D,所以D[i]=D1[i] + D2[i],例如第一个元素(列表)看起来像这样:

D=[["a "," "," "," "," "," ","a "," ","o"," ","x"," "],...]

请帮助我,我是python的新手

3 个答案:

答案 0 :(得分:0)

如果您不想更改D1,请先将D1复制到D。 然后在python中使用extend方法。它将list2的所有元素添加到list1。

这是一个简单的代码: 尽管此代码的时间复杂度为O(n ^ 2),但可以改进。

D1=[["a "," "," "," "," "," "],["b "," ","o"," "," "," "],["c ","x"," "," "," "," "],["d "," "," "," "," "," "],["e "," "," "," "," "," "]]

D2=[["a "," ","o"," ","x"," "],
["b "," "," "," "," "," "],["c "," "," "," "," "," "],["d "," "," "," "," "," "],["e "," "," "," "," "," "]]

D = D1 [:]
for i in range (len (D)):
    D[i].extend (D2 [i])
print D
  

另外一点:请按照@Patrick的说明进行操作   Artner。否则,您的问题更有可能被否决,   可能会导致您无法提出进一步的问题。

答案 1 :(得分:0)

尝试一下:

RewriteEngine On
RewriteBase /

RewriteRule ^images/background\.png$ includes/adaptive-images.php

# redirects non-www to www
RewriteCond %{HTTP_HOST} ^my-first.domain\.com [NC]
RewriteRule (.*) http://www.my-first-domain.com/$1 [R=301,L]

# redirects /index.php to /
RewriteCond %{IS_SUBREQ} false
RewriteRule ^index\.php$ http://www.my-first-domain.com/ [R=301,L]

# redirects missing files and directories to home (instead of error document)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://www.my-first-domain.com/ [R=301,L]

如果长度不同,它将削减其余部分并前进到D = [i+j for i,j in zip(D1,D2)] D1的最小值。如果您要相反,请使用D2,如下所示:

zip_longest

但是如果from itertools import zip_longest D = [i+j for i,j in zip_longest(D1,D2)] D1具有相同的长度,则两者都可以工作。

答案 2 :(得分:0)

直截了当(D[i] = D1[i] + D2[i]),最简单的方法是使用理解列表。假设len(D1) == len(D2) ,:

 D = [ D1[i] + D2[i] for i in range(len(D1)) ]

会做。