久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

Python:用漸進式數字重命名列表中的重復項而不對

Python: Rename duplicates in list with progressive numbers without sorting list(Python:用漸進式數字重命名列表中的重復項而不對列表進行排序)
本文介紹了Python:用漸進式數字重命名列表中的重復項而不對列表進行排序的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

給定這樣的列表:

mylist = ["name", "state", "name", "city", "name", "zip", "zip"]

我想通過附加一個數字來重命名重復項以獲得以下結果:

I would like to rename the duplicates by appending a number to get the following result:

mylist = ["name1", "state", "name2", "city", "name3", "zip1", "zip2"]

我不想更改原始列表的順序.針對此相關 Stack Overflow 問題建議的解決方案對列表進行排序,我不想這樣做.

I do not want to change the order of the original list. The solutions suggested for this related Stack Overflow question sorts the list, which I do not want to do.

推薦答案

我會這樣做.我把它寫成一個更通用的實用函數,因為人們似乎喜歡這個答案.

This is how I would do it. I wrote this into a more generalized utility function since people seem to like this answer.

mylist = ["name", "state", "name", "city", "name", "zip", "zip"]
check = ["name1", "state", "name2", "city", "name3", "zip1", "zip2"]
copy = mylist[:]  # so we will only mutate the copy in case of failure

from collections import Counter # Counter counts the number of occurrences of each item
from itertools import tee, count

def uniquify(seq, suffs = count(1)):
    """Make all the items unique by adding a suffix (1, 2, etc).

    `seq` is mutable sequence of strings.
    `suffs` is an optional alternative suffix iterable.
    """
    not_unique = [k for k,v in Counter(seq).items() if v>1] # so we have: ['name', 'zip']
    # suffix generator dict - e.g., {'name': <my_gen>, 'zip': <my_gen>}
    suff_gens = dict(zip(not_unique, tee(suffs, len(not_unique))))  
    for idx,s in enumerate(seq):
        try:
            suffix = str(next(suff_gens[s]))
        except KeyError:
            # s was unique
            continue
        else:
            seq[idx] += suffix

uniquify(copy)
assert copy==check  # raise an error if we failed
mylist = copy  # success

如果您想在每個計數前添加下劃線,您可以執行以下操作:

If you wanted to append an underscore before each count, you could do something like this:

>>> mylist = ["name", "state", "name", "city", "name", "zip", "zip"]
>>> uniquify(mylist, (f'_{x!s}' for x in range(1, 100)))
>>> mylist
['name_1', 'state', 'name_2', 'city', 'name_3', 'zip_1', 'zip_2']

...或者如果您想改用字母:

...or if you wanted to use letters instead:

>>> mylist = ["name", "state", "name", "city", "name", "zip", "zip"]
>>> import string
>>> uniquify(mylist, (f'_{x!s}' for x in string.ascii_lowercase))
>>> mylist
['name_a', 'state', 'name_b', 'city', 'name_c', 'zip_a', 'zip_b']

注意:這不是最快的算法;為此,請參閱 ronakg 的答案.上述函數的優點是易于理解和閱讀,除非您有一個非常大的列表,否則您不會看到太大的性能差異.

NOTE: this is not the fastest possible algorithm; for that, refer to the answer by ronakg. The advantage of the function above is it is easy to understand and read, and you're not going to see much of a performance difference unless you have an extremely large list.

這是我在單行中的原始答案,但是順序沒有保留,它使用 .index 方法,這是非常次優的(如 DTing的答案).請參閱 queezz 的答案,了解保持秩序的良好雙線".

Here is my original answer in a one-liner, however the order is not preserved and it uses the .index method, which is extremely suboptimal (as explained in the answer by DTing). See the answer by queezz for a nice 'two-liner' that preserves order.

[s + str(suffix) if num>1 else s for s,num in Counter(mylist).items() for suffix in range(1, num+1)]
# Produces: ['zip1', 'zip2', 'city', 'state', 'name1', 'name2', 'name3']

這篇關于Python:用漸進式數字重命名列表中的重復項而不對列表進行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 欧美精品在线播放 | 国产区精品在线观看 | 欧美日韩亚洲国产 | 毛片国产| www在线视频| 伊人一二三 | 欧美 日韩 中文 | 在线视频 亚洲 | 91免费看片 | 国产情侣久久 | 成人毛片一区二区三区 | 国产在线视频一区二区 | 国产一级片在线播放 | 国产乱码精品1区2区3区 | 国产做a爱免费视频 | 在线一区| 久久久蜜臀国产一区二区 | 超碰高清| 免费精品 | 午夜小影院 | 亚洲视频免费观看 | 羞羞在线观看视频 | 欧美一区二 | 人人性人人性碰国产 | av入口| 精品视频在线一区 | 激情国产视频 | 亚洲精品99| 亚洲欧美高清 | 毛片.com| av在线免费观看网址 | 国产亚洲精品a | 国精品一区二区 | 日韩欧美在线免费观看 | 亚洲一区二区三区在线免费观看 | 国产黄色网址在线观看 | 九九热精品在线 | 欧美激情在线观看一区二区三区 | 国产精品精品 | 黑人一级片视频 | 人成在线视频 |