简体   繁体   English

如何使用字符串元组及其替换来替换列表中的字符串?

[英]How to replace strings in a list using tuples of strings and their replacements?

I have a list of player ranks attributed to players. 我有一个归属于玩家的玩家排名列表。 In addition to this, I have a list of tuples of ranks... 除此之外,我还有一系列排名的元组...

rank_database = [("Unprocessed Rank", "Processed Rank"), ("Unprocessed Rank 2", "Processed Rank 2")]

What I would like to do is, for every item in the player ranks list, process them through the rank database --- like find and replace. 我想要做的是,对于玩家排名列表中的每个项目,通过排名数据库处理它们 - 比如查找和替换。

So, before replacement: 所以,在更换之前:

player_ranks = ["Unprocessed Rank", "Unprocessed Rank 2"]

After replacement: 更换后:

player_ranks = ["Processed Rank", "Processed Rank 2"]

Essentially, I would like to use rank_database to perform a find and replace operation on the player_ranks list. 基本上,我想使用rank_databaseplayer_ranks列表上执行查找和替换操作。

Proposed Solution 提出的解决方案

My idea was to try to use the tuples with the str.replace method as follows... 我的想法是尝试使用str.replace方法的元组如下...

player_ranks = ["Unprocessed Rank", "Unprocessed Rank 2"]
rank_database = [("Unprocessed Rank", "Processed Rank"), ("Unprocessed Rank 2", "Processed Rank 2")]

for x in player_ranks:
    for y in rank_database:
        print("Changed "+x+" to")
        if x == y[0]:
            player_ranks[x].replace(rank_database[y]) #Line 5
            print (x)
            break
        else:
            continue
print("Finished!")

When I execute the code, since ("Unprocessed Rank", "Processed Rank") is a tuple found at rank_database[i] , I'm hoping this will sort of "inject" the tuple as the replacement strings in the str.replace method. 当我执行的代码,因为("Unprocessed Rank", "Processed Rank")是发现了一个元组rank_database[i] ,我希望这将整理的“注入”的元组作为替换字符串str.replace方法。

So, when executing the code, Line 5 should look like... 因此,在执行代码时,第5行应该看起来像......

rank.replace(("Unprocessed Rank", "Processed Rank"))

Would this be a possible solution, or is this not possible, and would other solutions be more appropriate? 这是一个可能的解决方案,或者这是不可能的,其他解决方案是否更合适? This is for a personal project, so I would prefer to get my own solution working. 这是一个个人项目,所以我更愿意让我自己的解决方案工作。

I'm making these assumptions: 我正在做这些假设:

  1. The "unprocessed" ranks in your database are unique, because otherwise you'll have to add a way to determine which tuple is the "correct" mapping from that unprocessed rank to a processed one. 数据库中的“未处理”排名是唯一的,因为否则您将不得不添加一种方法来确定哪个元组是从未处理的排名到已处理排名的“正确”映射。

  2. Returning a new list of processed ranks is as good as mutating the original list. 返回新的已处理等级列表与改变原始列表一样好。

  3. Your data will all fit in memory easily, because this will take at least twice the memory your database already uses. 您的数据将很容易适合内存,因为这将至少占用数据库已使用的内存的两倍。

Your database should be stored as a dict , or at least should be converted into one for the kind of work you're doing, since all you're doing is mapping unique(?) keys to values. 您的数据库应该存储为dict ,或者至少应该转换为您正在进行的工作类型,因为您所做的只是将唯一(?)键映射到值。 The dict initializer can take an iterable of key-value pairs, which you already have. dict初始值设定项可以使用您已有的可迭代键值对。

Below, I've created a stand-alone function to do the work. 下面,我创建了一个独立的功能来完成这项工作。

#!/usr/bin/env python3

def process_ranks(player_ranks, rank_database):
    rank_map = dict(rank_database)
    return [rank_map[rank] for rank in player_ranks]

def main():
    # Sample data.
    player_ranks = ['old' + str(n) for n in range(4)]
    # Database contains more rank data than we will use.
    rank_database = [
      ('old' + str(n), 'new' + str(n)) for n in range(40)
      ]

    print("Original player ranks:")
    print(player_ranks)
    processed_ranks = process_ranks(player_ranks, rank_database)
    print("Processed player ranks:")
    print(processed_ranks)
    return

if "__main__" == __name__:
    main()

Output: 输出:

Original player ranks:
['old0', 'old1', 'old2', 'old3']
Processed player ranks:
['new0', 'new1', 'new2', 'new3']

If you really do need to mutate the original list, you could replace its contents with a slightly different call to process_ranks in main with: 如果你真的需要改变原始列表,你可以使用与main process_ranks略有不同的调用来替换它的内容:

    player_ranks[:] = process_ranks(player_ranks, rank_database)

In general, though, I find preserving the original list and creating a new processed_ranks list is easier to code and especially to debug. 但是,一般情况下,我发现保留原始列表并创建新的processed_ranks列表更容易编码,尤其是调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM