压缩QS中的元组

时间:2013-05-28 04:05:59

标签: python python-3.x tuples list-comprehension

将这个元组列表转换为更简单的元组列表的Pythonic方法是什么?

import urllib.parse
QS='field=var1&save=stringA&field=var2&save=&field=var3&save=stringC'
urllib.parse.parse_qsl(QS, keep_blank_values=True)
>>> [('field', 'var1'), ('save', 'stringA'), ('field', 'var2'), ('save', ''), ('field', 'var3'), ('save', 'stringC')]

Python魔法发生在这里

>>> [('var1', 'stringA'), ('var2', ''), ('var3', 'stringC')]

1 个答案:

答案 0 :(得分:1)

>>> data = [('field', 'var1'), ('save', 'stringA'), ('field', 'var2'), ('save', ''), ('field', 'var3'), ('save', 'stringC')]
>>> [(field[1], save[1]) for field, save in zip(*[iter(data)]*2)]
[('var1', 'stringA'), ('var2', ''), ('var3', 'stringC')]

How does zip(*[iter(s)]*n) work in Python?

另一种方式:

>>> items = (x[1] for x in data)
>>> list(zip(*[items]*2))
[('var1', 'stringA'), ('var2', ''), ('var3', 'stringC')]