【发布时间】:2017-04-14 17:20:26
【问题描述】:
我有一个这样的列表:
l = [[1,4], [3,6], [5,4]]
我想用“:”加入内部列表。我想要的结果是:
l = ['1:4', '3:6', '5:4']
如何用 Python 实现它?
【问题讨论】:
我有一个这样的列表:
l = [[1,4], [3,6], [5,4]]
我想用“:”加入内部列表。我想要的结果是:
l = ['1:4', '3:6', '5:4']
如何用 Python 实现它?
【问题讨论】:
您可以使用列表推导来实现:
[':'.join(map(str, x)) for x in l]
【讨论】:
l = [[1,4], [3,6], [5,4]]
fl = []
for x in l:
fl.append(str(x[0])+':'+str(x[1]))
print(fl) # Final List, also you can do: l = fl
但是,我认为你想做字典,如果这是真的,你必须这样做:
l = [[1,4], [3,6], [5,4]]
fd = {}
for x in l:
fd[x[0]] = x[1]
print(fd) # Final Dictionary
解释:
l = [[1,4], [3,6], [5,4]] # Your list
fl = [] # New list (here will be the result)
for x in l: # For each item in the list l:
fl.append(str(x[0])+':'+str(x[1])) # Append the first part [0] of this item with ':' and the second part [1].
print(fl)
使用字典:
l = [[1,4], [3,6], [5,4]] # Your list
fd = {} # New dictionary
for x in l: # For each item in the list l:
fd[x[0]] = x[1] # Make a key called with the first part of the item and a value with the second part.
print(fd) # Final Dictionary
您还可以更轻松地制作字典:
l = [[1,4], [3,6], [5,4]]
l = dict(l) # Make a dictionary with every sublist of the list (it also works with tuples), the first part of the sublist is the key, and the second the value.
【讨论】:
你可以这样做:
final_list = []
for i in l:
a = str(i[0])+':'+str(i[1])
final_list.append(a)
print(final_list)
【讨论】: