【问题标题】:How to remove something from one list and add it to another in python如何从一个列表中删除某些内容并将其添加到python中的另一个列表中
【发布时间】:2022-11-15 09:05:42
【问题描述】:

我有一个嵌套列表,其中某些元素的开头带有 [x]。我希望函数删除这些元素并将它们移动到 list1 中的最后一个列表(在索引 2 处)。但它应该在将其放入最后一个列表之前从中删除 [x] 。它还应该计算从每个列表中删除了多少。

例如:

list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']

# After:

list1 = [['stretch'], ['school'], ['sleep','midterm', 'homework', 'eat', 'final']]

# Output:
# 2 removed from 1st list
# 1 removed from 2nd list

【问题讨论】:

  • 请添加您尝试过的代码

标签: python list nested-lists


【解决方案1】:

这就是您要这样做的方式:

list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']]
for x in range(0,len(list1)-1):
    lst = list1[x]
    count =  0
    for i in range(0,len(lst)-1):
        str = lst[i]
        if str[0:3] == "[x]":
            list1.append(str[2:])
            count += 1
    print(f"{count} items were removed from list {x+1}" )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多