有没有一种简单的方法可以将双打列表转换为双打列表?
例如:
[1.0, 2.0, 3.0]
进入
[[1.0], [2.0], [3.0]]
我正在使用的代码需要第二个作为一堆函数的输入,但是有两个相同数据的副本很烦人。
答案 0 :(得分:18)
只需使用list-comprehension包装列表中的每个元素:
l = [1.0, 2.0, 3.0]
print [[x] for x in l]
[[1.0], [2.0], [3.0]]
答案 1 :(得分:2)
作为列表推导的替代方法,您可以尝试map
:
>>> map(lambda x: [x], l)
[[1.0], [2.0], [3.0]]
通过将lambda
函数(此处为对象并将其放入列表中)依次应用于l
的每个元素,可以得到所需的结果。
在Python 3 map
中返回一个迭代器,所以使用list(map(lambda x: [x], l))
来获取列表。
对于map
的小型列表,使用floats
的速度大约是列表推导的两倍,因为构建lambda
函数会产生很小的开销:
>>> %timeit [[x] for x in l]
1000000 loops, best of 3: 594 ns per loop
>>> %timeit map(lambda x: [x], l)
1000000 loops, best of 3: 1.25 us per loop
对于较长的列表,两者之间的时间差距开始关闭,但列表理解仍为preferred option in the Python community。
答案 2 :(得分:0)
可能没有必要,但如果列表理解是神秘的,这里是使用for循环的一般解决方案:
def convert(l):
converted = []
if isinstance(l, list):
if len(l) > 0:
for n in l:
converted.append([n])
return converted
l = [1.0, 2.0, 3.0]
print convert(l)
您还可以检查列表中的每个元素是否为浮点数,如果其中一个元素不是,则引发错误:
class NotFloatError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
def convert(l):
converted = []
if isinstance(l, list):
if len(l) > 0:
for n in l:
if isinstance(n, float):
converted.append([n])
else:
raise NotFloatError("An element in the list is not a float.")
return converted
l = [1.0, 2.0, 3.0]
print convert(l)
答案 3 :(得分:0)
a = [1.0, 2.0, 3.0]
for x in a:
a = [x]
print a