【问题标题】:Join sublist in a list in python when the sublists are still items in the big list当子列表仍然是大列表中的项目时,在python中的列表中加入子列表
【发布时间】:2017-04-14 17:20:26
【问题描述】:

我有一个这样的列表:

l = [[1,4], [3,6], [5,4]]

我想用“:”加入内部列表。我想要的结果是:

l = ['1:4', '3:6', '5:4']

如何用 Python 实现它?

【问题讨论】:

标签: python list join


【解决方案1】:

您可以使用列表推导来实现:

[':'.join(map(str, x)) for x in l]

【讨论】:

  • @detuvoldo 太棒了!如果您的问题得到解决,请随时点击左侧的绿色勾号来投票/接受答案!
【解决方案2】:
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.

【讨论】:

    【解决方案3】:

    你可以这样做:

    final_list = []
    for i in l:
        a = str(i[0])+':'+str(i[1])
        final_list.append(a)
    print(final_list)
    

    【讨论】:

      猜你喜欢
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 2020-02-23
      • 1970-01-01
      相关资源
      最近更新 更多