【问题标题】:Remove element from list and add to another从列表中删除元素并添加到另一个
【发布时间】:2022-01-01 07:40:52
【问题描述】:

为了好玩,我一直在玩 python,我想知道如何从包含名称列表(例如 Lst1.txt)的文本文件中删除随机名称,并将其插入到名称的新文本文件中删除(Lst2.txt),以便每次我运行该函数时它都会更新两个文件。我有一个 .py 文件,它对文件中定义的 2 个列表执行此操作。当我必须关闭计算机并必须重新启动 .py 文件时,我想拥有此使用文件

例如,如果 Lst1.txt 的名称为“John Smith、Jane Doe、John Johnson”,我运行该函数,它会选择一个随机名称,将其从 Lst1.txt 中删除,并将其添加到 Lst2.txt

然后 Lst1.txt 将是“约翰·史密斯,约翰·约翰逊”, 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"

【问题讨论】:

标签: python


【解决方案1】:

问题似乎围绕着“如何从列表中随机选择一项?”

列表可以被索引(从0开始)。所以选择一个随机索引并抓取该索引处的项目。

>>> 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']
>>>

【讨论】:

    【解决方案2】:

    您可以做的一件事是将第一个文件的名称存储在一个列表中,并使用random.choice() 从中取出一个随机值,并将其写入第二个文件并将剩余的附加到第一个文件中,例如这……

    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")
    

    输出:-

    在 0.0007908344268798828 秒内执行

    【讨论】:

    • “在 0.0007908344268798828 秒内执行”与问题有什么关系?
    • 它只是一个确认输出,以便将值成功写入第二个文件,中间没有任何错误
    猜你喜欢
    • 2015-04-24
    • 2016-02-26
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多