我有以下元组列表:
>>>lis = df['vals'].values.tolist()
>>>lis
[[('apple', 'FRUIT'),
('$', 'SYM'),
('6.00', 'X'),
('bannana', 'FRUIT'),
('$', 'SYM'),
('4.00', 'X')]]
如何将其重新格式化为:
lis = [['apple: $ 6.00', 'bannana: $ 4.00']]
我试图:
list_comp = [item for sublist in lis for item in sublist]
list_comp = [' '.join(item) for t in list_comp for item in [t]]
但是我不知道如何设置:
和上述格式。
答案 0 :(得分:3)
您可以使用理解并将": $ "
与元组元素连接起来:
print [lis[0][i][0] + ": $ " + lis[0][i+2][0] for i in range(0,len(lis[0]),3)]
答案 1 :(得分:3)
首先,定义一个函数:
>>> def format_tuple(fruit, sym, x):
... return "{}: {} {}".format(fruit, sym, x)
...
然后,
>>> my_list
[[('apple', 'FRUIT'), ('$', 'SYM'), ('6.00', 'X'), ('bannana', 'FRUIT'), ('$', 'SYM'), ('4.00', 'X')]]
>>> my_list = my_list[0]
>>> by_three = (my_list[i:i + 3] for i in range(0,len(my_list), 3))
>>> [format_tuple(*(c[0] for c in chunk)) for chunk in by_three]
['apple: $ 6.00', 'bannana: $ 4.00']
而且,我想如果你真的希望它包含在一个列表中,最后一行可能是:
>>> [[format_tuple(*(c[0] for c in chunk)) for chunk in by_three]]
[['apple: $ 6.00', 'bannana: $ 4.00']]