[英]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? 无需手动编辑现有列表的结构,以便可以执行for循环?
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)
是整数。 (10.5,)
is a tuple of one integer. (10.5,)
是一个整数的元组。
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. 之所以起作用是因为@eumiro指出(10.5)实际上是一个浮点数而不是一个元组。 Tuple would be (10.5,).
元组为(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: 如果您有一个像(10.5,)这样的实元组列表,则可以这样修改它:
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: 用pythonic的方式做:
sqvaluelist = [v[0]**2 for v in valuelist]
sqvaluelist = [v [0] ** 2 for v in valuelist]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.