更改Python中的列表列表

时间:2017-12-05 20:21:35

标签: python python-3.x

我有这个列表清单:

['(A; B)', '(C; D; E)', '(F)', '(G; H)', '(M)']

我想把它变成这样的东西:

[('A', 'B'), ('C', 'D', 'E'), ('F'), ('G', 'H'), ('M')]

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您从一个类似于列表的字符串列表开始。你必须遍历列表中的每个元素(每个字符串),修改它,以便Python将其理解为列表,然后将其提供给Python。

代码将是这样的:

original_list = ['(A; B)', '(C; D; E)', '(F)', '(G; H)', '(M)']
new_list = []  # Create the new_list empty
for item in original_list:  # Iterate through each element of the original_list
    new_list.append(tuple(item[1:-1].split(';')))  # This line transforms the string to a tuple and adds it to Python

print(new_list)
# outputs [('A', ' B'), ('C', ' D', ' E'), ('F',), ('G', ' H'), ('M',)]

第一次迭代中最复杂的一行:

  • item等于'(A; B)'
  • item[1:-1]切割字符串,删除第一个字符和最后一个字符(括号标记),留下'A; B'
  • item[1:-1].split(';')拆分该项目,创建一个列表。它使用';'作为分隔符,因此结果列表为['A', ' B']
  • tuple(item[1:-1].split(';'))只是将列表转换为元组,返回('A', ' B')
  • new_list.append(tuple(item[1:-1].split(';')))最后,我们将其附加到new_list

尝试理解这一步一步的解释。该代码相当于@WNG提供的一个内容。

答案 1 :(得分:0)

对于列表中的每个项目,删除括号并用分号分隔,然后获得列表列表

代码

myList = ['(A; B)', '(C; D; E)', '(F)', '(G; H)', '(M)']

new_List = []
for i in myList:
    # remove paranthesis
    remove_par_i = i[1:-1]
    # Split with semicolon
    split_i = remove_par_i.split(";")
    new_List.append(split_i)
print(new_List)