简体   繁体   中英

How can I extract these list and tuples into strings?

I have these lists and tuples and can't figure out how to extract the numbers out of them.

[('40', '50')] [('35', '45', '49')] [('02', '11')]

They are stored in three different variables, how can I extract them? I've tried the following:

chain.from_iterable(list_one)

but it gives me this:

<itertools.chain object at 0x1101415f8>

Expected output for [('40', '50')] is 40 50

Expected output for [('35', '45', '49')] is 35 45 49

Expected output for [('02', '11')] is 02 11

Use chain to chain your lists together and then iterate through them. Then you can unpack in the print call to get every sub-element element printed out.

So, if for example your lists are named l1 , l2 and l3 as so:

l1, l2, l3 = [('40', '50')], [('35', '45', '49')], [('02', '11')]

You're able to access each individual and print it with:

for sub in chain(l1, l2, l3):
    print(*sub)

Yields:

40 50
35 45 49
02 11

Now, the output from your original attempt, namely:

<itertools.chain object at 0x1101415f8>

is due to the fact that chain returns an iterator object and that is its representation in the Python REPL. Remember, iterators are meant to be iterated over.

To get each seperately as string:

 output = ""
    a = [('02', '11')]
    for i in a:
        for x in i:
            output = output + " " + x

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