簡體   English   中英

如何從一個列表中刪除某些內容並將其添加到 python 中的另一個列表中

[英]How to remove something from one list and add it to another in python

我有一個嵌套列表,其中某些元素的開頭帶有 [x]。 我希望 function 刪除這些元素並將它們移動到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

這就是你要這樣做的方式:

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

items = 0
for i in range(len(list1)-1):
    for j in list1[i]:
        if "[x]" in j:
            new_list[2].append(j.replace("[x]", ""))
            items += 1
        else:
            new_list[i].append(j)

print(list1, new_list, items)

我認為你有一個數據結構問題。 你的代碼不應該匹配用戶輸入,你應該盡快擺脫它,並將顯示和存儲分開。 話雖這么說,您仍然可以通過盡快放棄愚蠢來朝着這些變化邁出一步:

運行示例:

$ python code.py
[['[x]homework', '[x]eat', 'stretch'], ['[x]final', 'school'], ['sleep', 'midterm']]
changed count is 0
[['stretch'], ['school'], ['sleep', 'midterm', 'homework', 'eat', 'final']]

源代碼如下

def main():
    list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']]
    print(list1)
    count, list2 = process(list1)
    print(f'changed count is {count}')
    print(list2)
         
def parse(silly_item):
    if silly_item.startswith('[x]'):
        finished = True
        raw_item = silly_item[3:]
    else:
        finished = False
        raw_item = silly_item
    return finished, raw_item

def process(silly_data_format):
    todos, done = silly_data_format[:-1], silly_data_format[-1]
    count = 0
    new_todos = []
    new_done = done[:]
    for todo in todos:
        new_todo = []
        for silly_item in todo:
            finished, raw_item = parse(silly_item)
            target = new_done if finished else new_todo
            target.append(raw_item)
        new_todos.append(new_todo)
    new_silly_data_format = new_todos + [new_done]
    return count, new_silly_data_format

if __name__ == '__main__':
    main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM