簡體   English   中英

用一個列表中的兩個或多個替換一個項目的pythonic方法

[英]pythonic way of replacing one item with two or more in a list

我如何以兩個或更多的方式替換列表中的一個項目? 我正在使用拆分和索引來做它,它看起來非常非python。

我希望這樣的東西存在:

values = [ "a", "b", "old", "c" ]
[ yield ["new1", "new2"] if item == "old" else item for item in values ]
// return [ "a", "b", "new1", "new2", "c" ]

執行此操作的最佳方法是使用itertools.chain.from_iterable

itertools.chain.from_iterable(
  ("new1", "new2") if item == "old" else (item, ) for item in values)

您面臨的“每個項目的多個項目”問題可通過創建嵌套列表,然后將其展開來解決。 通過制作所有項目元組(單項元組,我們只想要一個),我們可以實現這一點。

當然,如果你需要一個列表而不是一個迭代器,請通過調用list()來包裝整個事件。

我認為你有正確的想法。 但是,列表推導並不總是很合適。

這是使用列表連接的解決方案:

values = [ 'a', 'b', 'old', 'c' ]

def sub1(values, old, new):
    newvalues = []
    for item in values:
        if item == old:
            newvalues += new
        else:
            newvalues += [item]
    return newvalues

print sub1(values, 'old', ['new1', 'new2'])

這里有一個使用發電機:

def sub2(values, old, new):
    for item in values:
        if item == old:
            for i in new:
                yield i
        else:
            yield item

for i in sub2(values, 'old', ['new1', 'new2']):
    print i

下面是多值一般*的解決方案,如OP要求在這里

subs = {'old':("new1", "new2"), 'cabbage':('ham','and','eggs')}
itertools.chain.from_iterable(
  subs[item] if item in subs else (item, ) for item in values)

使用基於append的方法不會變得更容易或更難:

def sub1(values, subs):
    newvalues = []
    for item in values:
        if item in subs:
            newvalues += subs[item]
        else:
            newvalues += [item]
    return newvalues

*如果您的舊物品不可用,那么這將不起作用,您需要使它們可以清洗或找出另一個數據結構。 你還會比編寫平等測試更喜歡它。

好。 功能更多,但我不確定它真的更像'Pythonic':

reduce(operator.add, [ [x] if x != 'old' else ['new1','new2']  for x in values ] )

真的和另一個答案一樣,除了減少而不是itertools。

Reduce是一種標准的函數式編程習慣,因此它應該更加明顯。

itertools.chain.from_iterable很酷,但有點模糊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM