[英]How to remove a random element from a list and add it to another list in 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.