嵌套列表添加

时间:2017-10-21 12:49:29

标签: python-2.7 nested-lists

我有一个名为a的嵌套列表:

a = [[0, 1, 2, 3, 4], [10, 11, 12, 13, 14]]

我想要的输出是一个新列表(b),其中包含a中的第一个列表:[0, 1, 2, 3, 4]。然后我想在此列表中附加[10, 11, 12, 13, 14]中添加到[0, 1, 2, 3, 4]中最后一个数字的所有值:

b = [0, 1, 2, 3, 4, 14, 15, 16, 17, 18]

1 个答案:

答案 0 :(得分:0)

# Your First List
a =[[0, 1, 2, 3, 4], [10, 11, 12, 13, 14]]

# Your Second List which is initalized as empty.
b = []

# Adding first list from (a) which is a[0] into second list 
# a[0] = [0, 1, 2, 3, 4]
# a[1] = [10, 11, 12, 13, 14]

b.extend(a[0])

# b = [0, 1, 2, 3, 4]

# I then want to append to this list all of the values in [10, 11, 12, 13, 14] added 
# the last number in [0, 1, 2, 3, 4].

# a[0] = [0, 1, 2, 3, 4]
# a[0][-1] = 4 

last_val = a[0][-1]


second_list = a[1] # [10, 11, 12, 13, 14]

for item in second_list:
  b.append(item+last_val)


print(b)  

# b = [0, 1, 2, 3, 4, 14, 15, 16, 17, 18]