[英]Remove element from list and add to another
I have been messing around with python for fun and I want to know how to remove a random name from a text file that contains a list of names (ex Lst1.txt) and inset it to a new text file of the names removed (Lst2.txt) so that every time I run the function it updates both files.为了好玩,我一直在搞乱 python,我想知道如何从包含名称列表(例如 Lst1.txt)的文本文件中删除随机名称,并将其插入到已删除名称的新文本文件中(Lst2 .txt),这样每次我运行 function 时,它都会更新这两个文件。 I have a.py file that does this for 2 lists that are defined in the file.
我有一个 .py 文件,它为文件中定义的 2 个列表执行此操作。 I want to have this use files for when I have to turn off the computer and have to relaunch the.py file
当我必须关闭计算机并必须重新启动 .py 文件时,我想拥有这个使用文件
So for example if Lst1.txt has the names "John Smith, Jane Doe, John Johnson" and I run the function it would then pick a random name, remove it from Lst1.txt, and add it to Lst2.txt例如,如果 Lst1.txt 的名称为“John Smith,Jane Doe,John Johnson”,我运行 function,它会选择一个随机名称,将其从 Lst1.txt 中删除,并将其添加到 Lst2.txt
Then Lst1.txt would then be "John Smith, John Johnson", And Lst2.txt would be "Jane Doe".那么 Lst1.txt 将是“John Smith, John Johnson”,而 Lst2.txt 将是“Jane Doe”。
When the last name from Lst1.txt is selected, the file would be empty while Lst2.txt would be "Jane Doe, John Smith, John Johnson" When the last name from Lst1.txt is selected, the file would be empty while Lst2.txt would be "Jane Doe, John Smith, John Johnson"
The question seems to center around "how can I select a random item from a list?"问题似乎集中在“我怎样才能 select 是列表中的随机项目?”
Lists can be indexed (starting from 0
).列表可以被索引(从
0
开始)。 So select a random index and grab the item at that index.所以 select 是一个随机索引并在该索引处获取项目。
>>> from random import randint
>>> lst = ["foo", "bar", "baz"]
>>> lst[randint(0, len(lst) - 1)]
'baz'
>>> item = lst[randint(0, len(lst)- 1)]
>>> item
'baz'
>>> lst.remove(item)
>>> lst
['foo', 'bar']
>>> lst = ["foo", "bar", "baz"]
>>> lst2 = []
>>> while lst:
... item = lst[randint(0, len(lst)- 1)]
... lst.remove(item)
... lst2.append(item)
...
>>> lst
[]
>>> lst2
['foo', 'baz', 'bar']
>>>
One thing that you can do is store the names of the 1st file in a list, and using random.choice()
take a random value out of it, and write it to the 2nd file and append the remaining to the 1st file like this...您可以做的一件事是将第一个文件的名称存储在列表中,并使用
random.choice()
从中取出一个随机值,并将其写入第二个文件,并将 append 其余的写入第一个文件,如下所示...
from random import choice
from time import time
start = time()
with open("sample1.txt") as Rf1:
data = Rf1.read().split(",")
name = choice(data)
Wf1, Wf2 = open("sample1.txt", "w"), open("sample2.txt", "w")
Wf2.write(data.pop(data.index(name)))
Wf1.write(",".join(data))
Wf1.close(); Wf2.close()
end = time()
print(f"Executed in {end-start} secs")
Output:- Output:-
Executed in 0.0007908344268798828 secs
在 0.0007908344268798828 秒内执行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.