第一个问题
我想知道如何在二维列表中使用 .strip() 函数,以便在列表中每个列表的每个元素中,您可以删除字符串中无用的空格。
这是我在 shell 中的尝试:
>>> questions = [['1986 ',' Baby', 'Shaw ', ' Welcome'],['1976',' fJKC','cbv bv ',' byt']]
>>> [['1986 ',' Baby', 'Shaw ', ' Welcome'],['1976',' fJKC','cbv bv ',' byt']]
>>> for z in range(len(questions)):
for t in range(len(questions[z])):
questions[z].append(questions[z][t].strip())
>>> questions
>>> [['1986 ', ' Baby', 'Shaw ', ' Welcome', '1986', 'Baby', 'Shaw', 'Welcome'], ['1976', ' fJKC', 'cbv bv ', ' byt', '1976', 'fJKC', 'cbv bv', 'byt']]
但是,这不是我希望它返回的方式。我的预期结果是在编写代码后,问题等于:
>>> questions
>>> [['1986', 'Baby', 'Shaw', 'Welcome'], ['1976', 'fJKC', 'cbv bv', 'byt']]
最佳答案
- 您不需要使用索引来迭代列表。只是迭代。
list.append
不改变项目;使用list[i] = ...
来改变项目。或list[:] = ...
更改所有项目。
下面是使用简单迭代和列表切片赋值 (list[:] = ...
) 来用列表理解就地替换项目的方法:
questions = [['1986 ',' Baby', 'Shaw ', ' Welcome'], ['1976',' fJKC','cbv bv ',' byt']]
for q in questions:
q[:] = [info.strip() for info in q]
# Alternatives
# q[:] = (info.strip() for info in q) # generator expression
# q[:] = map(str.strip, q) # `map` with unbound method `str.strip`
# question => [['1986', 'Baby', 'Shaw', 'Welcome'], ['1976', 'fJKC', 'cbv bv', 'byt']]
关于python - 将 .strip() 用于二维列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40689140/