简体   繁体   中英

how to split all first elements of tuples in list? (Python)

I made a list called conditionList looking like this:

('I'm a man.', 2, 5, 10), ('I'm 20 years old', 6, 8, 10), ('This is just another sentence', 5, 6 10)

This conditionList is the result of a zip function of 4 lists:

conditionlist = zip(sentence, variable1, variable2, variable3)

So every element of the list consists of a sentence followed by three numbers. However, I need a function which would result in the following list:

('I', 2, 5, 10), ('am', 2, 5, 10), ('a', 2, 5, 10), ('man.', 2, 5, 10), ('I', 6, 8, 10) etc.

In this way, every word is associated with the variables of the sentence they belong to.

How can I go from my conditionList to the desired list?

Thank you.

Presumably what you had is a typo, you just need a comprehension and str.split .

>>> l
(("I'm a man.", 2, 5, 10),
 ("I'm 20 years old", 6, 8, 10),
 ('This is just another sentence', 5, 6, 10))
>>> [(i, j, k, m) for p, j, k, m in l for i in p.split()]
[("I'm", 2, 5, 10),
 ('a', 2, 5, 10),
 ('man.', 2, 5, 10),
 ("I'm", 6, 8, 10),
 ('20', 6, 8, 10),
 ('years', 6, 8, 10),
 ('old', 6, 8, 10),
 ('This', 5, 6, 10),
 ('is', 5, 6, 10),
 ('just', 5, 6, 10),
 ('another', 5, 6, 10),
 ('sentence', 5, 6, 10)]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM