python - 将 .strip() 用于二维列表

标签 python list python-3.x matrix

第一个问题

我想知道如何在二维列表中使用 .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']]

最佳答案

  1. 您不需要使用索引来迭代列表。只是迭代。
  2. 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/

相关文章:

python - 如何在 Komodo Edit IDE 中编写宏?

java - ArrayList 在不同线程中为空

Python 使串行输出可供其他脚本访问

python - 绘制包含数百万行的列

Python请求,如何为每个请求绑定(bind)不同的源ip?

python - matplotlib 内联语法错误

python - alembic 并获取最后插入的值

python 列表项组合

python - 为什么内置的 python 帮助功能不显示所有可能的命令?

python - 双向链接哨兵列表中的 __next__ 和 __iter__ 方法