如何将值从一个列表传输到另一个列表?

时间:2013-04-10 18:39:28

标签: python python-2.7

假设您有3个列表

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

使用List3中的值,我想将'Fu'List2[0][2]转移到List1[0][2],因为List3的第一个值是3 ,这意味着从List2取第3个值(从0开始列出[2] [0] [2])并将其放在与List1相同的位置

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

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

我已经在那里待了几个小时但是无法让它工作!!

这是怎么做到的?

4 个答案:

答案 0 :(得分: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', '_']]

答案 1 :(得分: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) ]

答案 2 :(得分: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))

答案 3 :(得分:0)

for index in List3:
    first, second = index/3, index%3 
    List1[first][second] = List2[first][second]
print List1