在Python中转换嵌套列表

时间:2009-08-22 16:14:36

标签: python

假设我有这样的结构:

a = [
('A',
 ['D',
  'E',
  'F',
  'G']),
('B',
 ['H']),
('C',
 ['I'])
]

如何将其转换为:

a = [
('A', 'D'),
('A', 'E'),
('A', 'F'),
('A', 'G'),
('B', 'H'),
('C', 'I'),
]

谢谢你的时间!

3 个答案:

答案 0 :(得分:10)

尝试:

>>> a = [('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I'])]
>>> [(k,j) for k, more in a for j in more]
[('A', 'D'), ('A', 'E'), ('A', 'F'), ('A', 'G'), ('B', 'H'), ('C', 'I')]

当然,它只处理一个嵌套级别。

答案 1 :(得分:4)

这是一个简单的解决方案:

data = [
('A',
  ['D',
  'E',
  'F',
  'G']),
('B',
  ['H']),
('C',
  ['I'])
]

result = []

for x in data:
    for y in x[1]:
        result.append((x[0], y))

答案 2 :(得分:1)

(旁注)为什么你这样缩进?以下不是更具可读性吗?

a = [
('A', ['D', 'E', 'F', 'G']),
('B', ['H']),
('C', ['I'])
]