我想这样做:
def my_func(x):
x.extend('\n')
return x
var1 = [['a', 'b'], ['c', 'd']]
for item in var1:
var2 = my_func(item)
print(var2)
>>>
['a', 'b', '\n']
['c', 'd', '\n']
使用Lambda函数。当我尝试
var1 = [['a', 'b'], ['c', 'd']]
var_x = list(map(lambda x: x.extend('\n'), var1))
>>>
[None, None]
如何写呢???
答案 0 :(得分:3)
extend
就地改变list
并返回None
。你应该尝试使用类似的东西:
x + ['\n']
而不是:
x.extend('\n')
答案 1 :(得分:0)
我不明白为什么,但这里 :
var1 = [['a', 'b'], ['c', 'd']]
f = lambda x: list(map(lambda y: y.extend('\n'), x))
var2 = f(var1)
print(var1) # [['a', 'b', '\n'], ['c', 'd', '\n']]
或者,如果你想保留for
- 循环:
var1 = [['a', 'b'], ['c', 'd']]
f = lambda x: x + ['\n']
for sublist in var1:
var2 = f(sublist)
print(var2)
# ['a', 'b', '\n']
# ['c', 'd', '\n']