1

假设您有 3 个列表

List1 = [['_', '_', '_'], ['_', '_', '_'], ['_','_','_']]
List2 = [['Test', 'Word', 'Sudo'], ['Fu', 'Lu', 'Shou'], ['Ham', 'Spam', 'Eggs']]
List3 = [3, 5, 7,]

使用 from 的值List3,我想'Fu'List2[0][2]into转移List1[0][2],因为 的第一个值List3是 3,这意味着取第三个值(从 0 开始计算它的 list2[0][2])List2并将其放入同一个位置作为List1

使用 中的其他值的最终结果List3应该是:

List1 = [['_', '_', 'Fu'], ['_', 'Shou', '_'], ['Spam','_','_']]

我已经用了几个小时但无法让它工作!

这是怎么做到的?

4

4 回答 4

6
In [184]: List1 = [['_', '_', '_'], ['_', '_', '_'], ['_','_','_']]

In [185]: List2 = [['Test', 'Word', 'Sudo'], ['Fu', 'Lu', 'Shou'], ['Ham', 'Spam', 'Eggs']]

In [186]: List3 = [3, 5, 7,]

In [187]: for x in List3:
    q,r=divmod(x,3)
    List1[q][r]=List2[q][r]
   .....:     

In [188]: List1
Out[188]: [['_', '_', '_'], ['Fu', '_', 'Shou'], ['_', 'Spam', '_']]
于 2013-04-10T18:47:05.520 回答
2
>>> List1 = [['_', '_', '_'], ['_', '_', '_'], ['_','_','_']]
>>> List2 = [['Test', 'Word', 'Sudo'], ['Fu', 'Lu', 'Shou'], ['Ham', 'Spam', 'Eggs']]
>>> List3 = [3, 5, 7,]
>>> List4 = [item for sublist in List1 for item in sublist]
>>> List5 = [item for sublist in List2 for item in sublist]
>>> for val in List3:
...     List4[val] = List5[val]
>>> List1 = [ List4[i:i+3] for i in xrange(0,len(List4),3) ]
于 2013-04-10T18:59:04.613 回答
1
# If you must have original data as lists of lists:
def flat(lst):
    ret = []
    for x in lst:
        if hasattr(x, '__iter__'):
            ret += flat(x)
        else:
            ret.append(x)
    return ret

List1 = [['_', '_', '_'], ['_', '_', '_'], ['_','_','_']]
List2 = [['Test', 'Word', 'Sudo'], ['Fu', 'Lu', 'Shou'], ['Ham', 'Spam', 'Eggs']]
List3 = [3, 5, 7,]

lst1 = flat(List1)
lst2 = flat(List2)

# Now given flat lists, you can just do this:
def splitby(x, n=3):
    i = iter(x)
    while True:
        yield [next(i) for _ in range(n)]

for i in List3:
    lst1[i] = lst2[i]

print list(splitby(lst1))
于 2013-04-10T19:00:10.707 回答
1
for index in List3:
    first, second = index/3, index%3 
    List1[first][second] = List2[first][second]
print List1
于 2013-04-10T19:10:23.997 回答