a = [',', 'hello',',', 'pear']
for i in a:
d = 0
c = []
b = a[d]
if b == ',':
c.append(b)
d += 1
else:
d += 1
print c
这段代码中有两个逗号,但是结果只返回了一个。该如何修复?
d
重置为零,并清除了 c
。a = [',', 'hello',',', 'pear']
c = []
for b in a:
if b == ',':
c.append(b)
print c
a = [',', 'hello',',', 'pear']
c = [b for b in a if b == ',']
print c
您每次迭代都将一个空列表重新分配给c
。 您可以按照以下方式更改逻辑
c = [] # Initialized before the loop
for i in a:
if i[0] == ',':
c.append(b)
最好的写法是使用列表推导式,像这样:
c = [item for item in a if item == ","]
c = list(',' * a.count(','))
可能是另一种解决方案。 - Matthias[","] * a.count(",")
;) - thefourtheyefilter(','.__eq__, a)
。 - Steve Jessopa = [',', 'hello',',', 'pear']
print len([x for x in a if x == ','])
a
中删除逗号,还是找到逗号的位置,或者其他类似的操作? - user2357112