简体   繁体   中英

How to create a list of tuples Python?

Hello I am trying to create a list of tuples in this format :

train = [
    ('I love this sandwich.', 'pos'),
    ('This is an amazing place!', 'pos'),
    ('I feel very good about these beers.', 'pos'),
    ('This is my best work.', 'pos'),
    ("What an awesome view", 'pos'),
    ('I do not like this restaurant', 'neg'),
    ('I am tired of this stuff.', 'neg'),
    ("I can't deal with this", 'neg'),
    ('He is my sworn enemy!', 'neg'),
    ('My boss is horrible.', 'neg')
]

So basically I have a for loop which returns a string and I want to add a 'pos' or 'neg' to this string and create a list of these tuples.

I have tried different combinations but still not the result I want. Any hint will be much appreciated

This is my code :

if classifier.positiv > classifier.negativ:
   word = (input_text , 'pos')
else: 
   word = (input_text , 'neg')


nbTrain.extend(word)
nbTrain = tuple(nbTrain)

Simply do:

nbTrain = []

if classifier.positiv > classifier.negativ:
    word = (input_text , 'pos')
else: 
    word = (input_text , 'neg')


nbTrain.append(word)

只需使用列表理解即可:

train = [(input_text, 'pos') if is_positive(input_text) else (input_text, 'neg') for input_text in datasource]

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