I have the following list of tuples:
>>>lis = df['vals'].values.tolist()
>>>lis
[[('apple', 'FRUIT'),
('$', 'SYM'),
('6.00', 'X'),
('bannana', 'FRUIT'),
('$', 'SYM'),
('4.00', 'X')]]
How can I reformat it into:
lis = [['apple: $ 6.00', 'bannana: $ 4.00']]
I tried to:
list_comp = [item for sublist in lis for item in sublist]
list_comp = [' '.join(item) for t in list_comp for item in [t]]
However I do not get how to put the :
and the above format.
您可以使用理解并将": $ "
与元组元素连接起来:
print [lis[0][i][0] + ": $ " + lis[0][i+2][0] for i in range(0,len(lis[0]),3)]
First, define a function:
>>> def format_tuple(fruit, sym, x):
... return "{}: {} {}".format(fruit, sym, x)
...
Then,
>>> 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']
And, I suppose if you really want it wrapped in a list, that last line could be:
>>> [[format_tuple(*(c[0] for c in chunk)) for chunk in by_three]]
[['apple: $ 6.00', 'bannana: $ 4.00']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.