我想知道是否有一条快捷方式可以在Python列表中列出一个简单的列表.
我可以在for循环中做到这一点,但也许有一些很酷的"单行"?我用reduce尝试了,但是我收到了一个错误.
码
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
Run Code Online (Sandbox Code Playgroud)
错误信息
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
Run Code Online (Sandbox Code Playgroud) 我是python的新手,我需要一些帮助.
任务:给出一个清单 - > words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
我需要比较列表中每个字符串的第一个和最后一个元素,如果字符串中的第一个和最后一个元素相同,则递增计数.
给出的列表是:
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
Run Code Online (Sandbox Code Playgroud)
如果我手动尝试,我可以迭代列表中字符串的每个元素.
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
w1 = words[0]
print w1
aba
for i in w1:
print i
a
b
a
if w1[0] == w1[len(w1) - 1]:
c += 1
print c
1
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试迭代列表中所有字符串的所有元素时,使用FOR循环.
我收到一个错误.
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
c = 0
for i in words:
w1 = words[i]
if w1[0] == w1[len(w1) - 1]: …
Run Code Online (Sandbox Code Playgroud)