简体   繁体   中英

Removing tuples in a list

I have these lists:

sqvaluelist = []
valuelist = [(10.5,), (20.5,), (21.5,), (70.0,), (34.5,)]

I want to apply this code on the valuelist:

for value in valuelist:
    valuesquared = value*value
    sqvaluelist.append(valuesquared,)

but I received this error:

TypeError: can't multiply sequence by non-int of type 'tuple'

I think I know the reason behind this error, it is because every value is inside a separate tuple.

My question is, is there any way to take this values off their respective tuple, and just turn them into a list like

valuelist = [10.5, 20.5, 21.5, 70.0, 34.5]

without manually editing the structure of the existing list so that the for loop can be executed?

EDIT: I apologize! They are actually tuples! Added commas after each value. Sorry!

then just

import itertools
list(itertools.chain(*valuelist))

To make

valuelist = [(10.5,), (20.5,), (21.5,), (70.0,), (34.5,)]

into

valuelist = [10.5, 20.5, 21.5, 70.0, 34.5]

I'd use list comprehension

valuelist = [x[0] for x in valuelist]
valuelist = [(10.5), (20.5), (21.5), (70.0), (34.5)]

is a list of ints:

>>> [(10.5), (20.5), (21.5), (70.0), (34.5)]
[10.5, 20.5, 21.5, 70.0, 34.5]

(10.5) is an integer. (10.5,) is a tuple of one integer.

Therefore:

>>> sqvaluelist = [x*x for x in valuelist]
>>> sqvaluelist
[110.25, 420.25, 462.25, 4900.0, 1190.25]

Yes you can do so very easily in a one liner :

map(lambda x: x, valuelist)

This works because as @eumiro noted, (10.5) is actually a float and not a tuple. Tuple would be (10.5,).

To compute the squares it's as easy:

map(lambda x: x*x, valuelist)

If you have a list of real tuples like (10.5,), you can modify it like this:

map(lambda x: x[0], valuelist)
map(lambda x: x[0]*x[0], valuelist)

Just access the first element of each tuple:

>>> valuelist = [(10.5,), (20.5,), (21.5,), (70.0,), (34.5,)]
>>> sqvaluelist = [x[0]*x[0] for x in valuelist]
>>> sqvaluelist
[110.25, 420.25, 462.25, 4900.0, 1190.25]

Doing it in pythonic way:

sqvaluelist = [v[0]**2 for v in valuelist]

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