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

復制列表中的字符串并將整數后綴添加到新添加

Duplicate strings in a list and add integer suffixes to newly added ones(復制列表中的字符串并將整數后綴添加到新添加的字符串中)
本文介紹了復制列表中的字符串并將整數后綴添加到新添加的字符串中的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

假設我有一個列表:

l = ['a', 'b', 'c']

及其后綴列表:

l2 = ['a_1', 'b_1', 'c_1']

我想要的輸出是:

out_l = ['a', 'a_1', 'b', 'b_2', 'c', 'c_3']

結果是上面兩個列表的交錯版本.

我可以編寫常規的 for 循環來完成這項工作,但我想知道是否有更 Pythonic 的方式(例如,使用列表推導或 lambda)來完成它.

我嘗試過這樣的事情:

list(map(lambda x: x[1]+'_'+str(x[0]+1), enumerate(a)))# 這只返回 ['a_1', 'b_2', 'c_3']

此外,對于一般情況,即 l2 不一定是 l 派生的 2 個或更多列表,需要進行哪些更改?

解決方案

基準代碼,供參考.

功能

def cs1(l):定義_cs1(l):對于 i, x in enumerate(l, 1):產量 x產量 f'{x}_{i}'返回列表(_cs1(l))定義 cs2(l):out_l = [無] * (len(l) * 2)out_l[::2] = lout_l[1::2] = [f'{x}_{i}' for i, x in enumerate(l, 1)]返回out_l定義 cs3(l):返回列表(chain.from_iterable(zip(l, [f'{x}_{i}' for i, x in enumerate(l, 1)])))定義阿賈克斯(l):返回 [i for b in [[a, '{}_{}'.format(a, i)]for i, a in enumerate(l, start=1)]對于我在 b]def ajax_cs0(l):# 建議改進 ajax 解決方案return [j for i, a in enumerate(l, 1) for j in [a, '{}_{}'.format(a, i)]]克里斯(左):返回 [值對于 zip 中的對(l,[f'{k}_{j+1}' 對于 j,k 在 enumerate(l)])對于 val 成對]

Suppose I have a list:

l = ['a', 'b', 'c']

And its suffix list:

l2 = ['a_1', 'b_1', 'c_1']

I'd like the desired output to be:

out_l = ['a', 'a_1', 'b', 'b_2', 'c', 'c_3']

The result is the interleaved version of the two lists above.

I can write regular for loop to get this done, but I'm wondering if there's a more Pythonic way (e.g., using list comprehension or lambda) to get it done.

I've tried something like this:

list(map(lambda x: x[1]+'_'+str(x[0]+1), enumerate(a)))
# this only returns ['a_1', 'b_2', 'c_3']

Furthermore, what changes would need to be made for the general case i.e., for 2 or more lists where l2 is not necessarily a derivative of l?

解決方案

yield

You can use a generator for an elegant solution. At each iteration, yield twice—once with the original element, and once with the element with the added suffix.

The generator will need to be exhausted; that can be done by tacking on a list call at the end.

def transform(l):
    for i, x in enumerate(l, 1):
        yield x
        yield f'{x}_{i}'  # {}_{}'.format(x, i)

You can also re-write this using the yield from syntax for generator delegation:

def transform(l):
    for i, x in enumerate(l, 1):
        yield from (x, f'{x}_{i}') # (x, {}_{}'.format(x, i))

out_l = list(transform(l))
print(out_l)
['a', 'a_1', 'b', 'b_2', 'c', 'c_3']

If you're on versions older than python-3.6, replace f'{x}_{i}' with '{}_{}'.format(x, i).

Generalising
Consider a general scenario where you have N lists of the form:

l1 = [v11, v12, ...]
l2 = [v21, v22, ...]
l3 = [v31, v32, ...]
...

Which you would like to interleave. These lists are not necessarily derived from each other.

To handle interleaving operations with these N lists, you'll need to iterate over pairs:

def transformN(*args):
    for vals in zip(*args):
        yield from vals

out_l = transformN(l1, l2, l3, ...)


Sliced list.__setitem__

I'd recommend this from the perspective of performance. First allocate space for an empty list, and then assign list items to their appropriate positions using sliced list assignment. l goes into even indexes, and l' (l modified) goes into odd indexes.

out_l = [None] * (len(l) * 2)
out_l[::2] = l
out_l[1::2] = [f'{x}_{i}' for i, x in enumerate(l, 1)]  # [{}_{}'.format(x, i) ...]

print(out_l)
['a', 'a_1', 'b', 'b_2', 'c', 'c_3']

This is consistently the fastest from my timings (below).

Generalising
To handle N lists, iteratively assign to slices.

list_of_lists = [l1, l2, ...]

out_l = [None] * len(list_of_lists[0]) * len(list_of_lists)
for i, l in enumerate(list_of_lists):
    out_l[i::2] = l


zip + chain.from_iterable

A functional approach, similar to @chrisz' solution. Construct pairs using zip and then flatten it using itertools.chain.

from itertools import chain
# [{}_{}'.format(x, i) ...]
out_l = list(chain.from_iterable(zip(l, [f'{x}_{i}' for i, x in enumerate(l, 1)]))) 

print(out_l)
['a', 'a_1', 'b', 'b_2', 'c', 'c_3']

iterools.chain is widely regarded as the pythonic list flattening approach.

Generalising
This is the simplest solution to generalise, and I suspect the most efficient for multiple lists when N is large.

list_of_lists = [l1, l2, ...]
out_l = list(chain.from_iterable(zip(*list_of_lists)))


Performance

Let's take a look at some perf-tests for the simple case of two lists (one list with its suffix). General cases will not be tested since the results widely vary with by data.

Benchmarking code, for reference.

Functions

def cs1(l):
    def _cs1(l):
        for i, x in enumerate(l, 1):
            yield x
            yield f'{x}_{i}'

    return list(_cs1(l))

def cs2(l):
    out_l = [None] * (len(l) * 2)
    out_l[::2] = l
    out_l[1::2] = [f'{x}_{i}' for i, x in enumerate(l, 1)]

    return out_l

def cs3(l):
    return list(chain.from_iterable(
        zip(l, [f'{x}_{i}' for i, x in enumerate(l, 1)])))

def ajax(l):
    return [
        i for b in [[a, '{}_{}'.format(a, i)] 
        for i, a in enumerate(l, start=1)] 
        for i in b
    ]

def ajax_cs0(l):
    # suggested improvement to ajax solution
    return [j for i, a in enumerate(l, 1) for j in [a, '{}_{}'.format(a, i)]]

def chrisz(l):
    return [
        val 
        for pair in zip(l, [f'{k}_{j+1}' for j, k in enumerate(l)]) 
        for val in pair
    ]

這篇關于復制列表中的字符串并將整數后綴添加到新添加的字符串中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持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.伊人.com | 三级黄色片在线 | 欧美一区二区三区视频 | 中文精品久久 | 国产一区二区三区在线 | 国产1区2区在线观看 | 91精品国产色综合久久不卡蜜臀 | 97精品视频在线 | 日韩精品一区二区三区久久 | 久久久久久久久久久久久久国产 | 中文字幕一区在线观看视频 | 国产在线播 | 亚洲 精品 综合 精品 自拍 | 国偷自产av一区二区三区 | 中文字幕亚洲一区二区三区 | 本地毛片| 91人人视频在线观看 | 7777在线视频免费播放 | 免费xxxx大片国产在线 | 国产精品视频 | 亚洲一区电影 | 成人小视频在线免费观看 | 欧美日韩成人影院 | 国产一区二区三区四区三区四 | 看片91 | 日本三级视频 | 精久久| 国产专区在线 | 99久久99热这里只有精品 | 日本a v在线播放 | 日日夜夜狠狠操 | 欧美成人第一页 | 老头搡老女人毛片视频在线看 | 精品欧美色视频网站在线观看 | 我想看一级黄色毛片 | 日韩精品久久 | 日韩一区二区在线看 | av网站在线播放 | 亚洲天堂一区二区 | 日韩欧美操 | 亚洲精品在线播放 |