简体   繁体   中英

Convert a list of bigram tuples to a list of strings

I am trying to create Bigram tokens of sentences. I have a list of tuples such as

tuples = [('hello', 'my'), ('my', 'name'), ('name', 'is'), ('is', 'bob')]

and I was wondering if there is a way to convert it to a list using python, so it would look love this:

list = ['hello my', 'my name', 'name is', 'is bob']

thank you

Try this snippet:

list = [' '.join(x) for x in tuples]

join is a string method that contatenates all items of a list (tuple) within a separator defined in '' brackets.

Try this

list = [ '{0} {1}'.format(t[0],t[1]) for t in tuples ]

In general if you want to use both values of a tuple, you can use something like this:

my_list = []
for (first, second) in tuples:
    my_list.append(first+ ' '+ second)

In this case

my_list = [' '.join(x) for t in tuples]

should be fine

tuples = [('hello', 'my'), ('my', 'name'), ('name', 'is'), ('is', 'bob')] result=[] [result.append(k+" "+v) for k,v in tuples]

print(result)

output:

['hello my', 'my name', 'name is', 'is bob']

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