【问题标题】:Adding to a list using another command使用另一个命令添加到列表
【发布时间】:2017-05-01 20:21:18
【问题描述】:

我有这个脚本:

if line.startswith("Length="):
     #add line to list 

我想将返回到列表中的每一行作为单独的元素。如何一次添加一行?

【问题讨论】:

  • 欢迎来到 StackOverflow!请提供MCVE。这将使我们能够帮助您解决问题。目前尚不清楚您如何访问文件或如何写入文件。或者您如何将数据返回到列表中。我们需要 MCVE 才能真正提供帮助。
  • 一般情况下,您会使用.append().insert()。但是,需要更多上下文才能给出更具体的答案。

标签: python list


【解决方案1】:

应该这样做:

my_list = []

for line in my_file:
    if line.startswith("Length="):
        my_list.append(line)

append() 方法将传递的 obj 附加到现有列表中。

例子:

>>>a = [1, 2, 3]
>>>a.append(4)
>>>a
[1, 2, 3, 4]

【讨论】:

    【解决方案2】:

    如果您只想过滤列表或其他可迭代对象并将所有符合条件的元素保存在新列表中,您可以使用条件列表推导:

    original_list = ["Height=2", "Length=3", "Width=5", "Length=42"]
    length_only = [item for item in original_list if item.startswith("Length=")]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 2014-06-10
      • 2020-01-23
      • 1970-01-01
      相关资源
      最近更新 更多