第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何克隆或復(fù)制列表?

如何克隆或復(fù)制列表?

胡說叔叔 2019-05-20 16:18:39
在Python中克隆或復(fù)制列表有哪些選項(xiàng)?在使用時(shí)new_list = my_list,每次都會(huì)對(duì)new_list更改進(jìn)行任何修改my_list。為什么是這樣?
查看完整描述

5 回答

?
精慕HU

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊

菲利克斯已經(jīng)提供了一個(gè)很好的答案,但我想我會(huì)對(duì)各種方法進(jìn)行速度比較:

  1. 10.59秒(105.9us / itn) - copy.deepcopy(old_list)

  2. 10.16秒(101.6us / itn) - Copy()使用deepcopy復(fù)制類的純python 方法

  3. 1.488秒(14.88us / itn) - 純python Copy()方法不復(fù)制類(只有dicts / lists / tuples)

  4. 0.325秒(3.25us / itn) - for item in old_list: new_list.append(item)

  5. 0.217秒(2.17us / itn) - [i for i in old_list]列表理解

  6. 0.186秒(1.86us / itn) - copy.copy(old_list)

  7. 0.075秒(0.75us / itn) - list(old_list)

  8. 0.053秒(0.53us / itn) - new_list = []; new_list.extend(old_list)

  9. 0.039秒(0.39us / itn) - old_list[:]列表切片

所以最快的是列表切片。但請(qǐng)注意copy.copy(),list[:]并且list(list),與copy.deepcopy()python版本不同,它不會(huì)復(fù)制列表中的任何列表,字典和類實(shí)例,因此如果原件發(fā)生更改,它們也會(huì)在復(fù)制的列表中更改,反之亦然。

(這是腳本,如果有人有興趣或想提出任何問題:)

from copy import deepcopy


class old_class:

    def __init__(self):

        self.blah = 'blah'


class new_class(object):

    def __init__(self):

        self.blah = 'blah'


dignore = {str: None, unicode: None, int: None, type(None): None}


def Copy(obj, use_deepcopy=True):

    t = type(obj)


    if t in (list, tuple):

        if t == tuple:

            # Convert to a list if a tuple to 

            # allow assigning to when copying

            is_tuple = True

            obj = list(obj)

        else: 

            # Otherwise just do a quick slice copy

            obj = obj[:]

            is_tuple = False


        # Copy each item recursively

        for x in xrange(len(obj)):

            if type(obj[x]) in dignore:

                continue

            obj[x] = Copy(obj[x], use_deepcopy)


        if is_tuple: 

            # Convert back into a tuple again

            obj = tuple(obj)


    elif t == dict: 

        # Use the fast shallow dict copy() method and copy any 

        # values which aren't immutable (like lists, dicts etc)

        obj = obj.copy()

        for k in obj:

            if type(obj[k]) in dignore:

                continue

            obj[k] = Copy(obj[k], use_deepcopy)


    elif t in dignore: 

        # Numeric or string/unicode? 

        # It's immutable, so ignore it!

        pass 


    elif use_deepcopy: 

        obj = deepcopy(obj)

    return obj


if __name__ == '__main__':

    import copy

    from time import time


    num_times = 100000

    L = [None, 'blah', 1, 543.4532, 

         ['foo'], ('bar',), {'blah': 'blah'},

         old_class(), new_class()]


    t = time()

    for i in xrange(num_times):

        Copy(L)

    print 'Custom Copy:', time()-t


    t = time()

    for i in xrange(num_times):

        Copy(L, use_deepcopy=False)

    print 'Custom Copy Only Copying Lists/Tuples/Dicts (no classes):', time()-t


    t = time()

    for i in xrange(num_times):

        copy.copy(L)

    print 'copy.copy:', time()-t


    t = time()

    for i in xrange(num_times):

        copy.deepcopy(L)

    print 'copy.deepcopy:', time()-t


    t = time()

    for i in xrange(num_times):

        L[:]

    print 'list slicing [:]:', time()-t


    t = time()

    for i in xrange(num_times):

        list(L)

    print 'list(L):', time()-t


    t = time()

    for i in xrange(num_times):

        [i for i in L]

    print 'list expression(L):', time()-t


    t = time()

    for i in xrange(num_times):

        a = []

        a.extend(L)

    print 'list extend:', time()-t


    t = time()

    for i in xrange(num_times):

        a = []

        for y in L:

            a.append(y)

    print 'list append:', time()-t


    t = time()

    for i in xrange(num_times):

        a = []

        a.extend(i for i in L)

    print 'generator expression extend:', time()-t


查看完整回答
反對(duì) 回復(fù) 2019-05-20
?
鴻蒙傳說

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊

被告知 Python 3.3+ 添加list.copy()方法,它應(yīng)該像切片一樣快:

newlist = old_list.copy()


查看完整回答
反對(duì) 回復(fù) 2019-05-20
?
繁花如伊

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊

已經(jīng)有許多答案告訴你如何制作一個(gè)正確的副本,但沒有一個(gè)人說你為什么原來的'副本'失敗了。

Python不會(huì)將值存儲(chǔ)在變量中; 它將名稱綁定到對(duì)象。您的原始作業(yè)采用了所引用的對(duì)象并將其my_list綁定new_list。無論您使用哪個(gè)名稱,仍然只有一個(gè)列表,因此在引用它時(shí)所做的更改將在引用my_list時(shí)保持不變new_list。此問題的其他每個(gè)答案都為您提供了創(chuàng)建要綁定的新對(duì)象的不同方法new_list。

列表的每個(gè)元素都像一個(gè)名稱,因?yàn)槊總€(gè)元素都非唯一地綁定到一個(gè)對(duì)象。淺拷貝創(chuàng)建一個(gè)新列表,其元素綁定到與以前相同的對(duì)象。

new_list = list(my_list)  # or my_list[:], but I prefer this syntax# is simply a shorter way of:new_list = [element for element in my_list]

要使列表副本更進(jìn)一步,請(qǐng)復(fù)制列表引用的每個(gè)對(duì)象,并將這些元素副本綁定到新列表。

import copy  
# each element must have __copy__ defined for this...new_list = [copy.copy(element) for element in my_list]

這還不是一個(gè)深層副本,因?yàn)榱斜淼拿總€(gè)元素都可以引用其他對(duì)象,就像列表綁定到它的元素一樣。以遞歸方式復(fù)制列表中的每個(gè)元素,然后復(fù)制每個(gè)元素引用的每個(gè)其他對(duì)象,依此類推:執(zhí)行深層復(fù)制。

import copy# each element must have __deepcopy__ defined for this...new_list = copy.deepcopy(my_list)

有關(guān)復(fù)制中的邊角情況的更多信息,請(qǐng)參閱文檔。


查看完整回答
反對(duì) 回復(fù) 2019-05-20
?
滄海一幻覺

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊

使用 thing[:]


>>> a = [1,2]

>>> b = a[:]

>>> a += [3]

>>> a

[1, 2, 3]

>>> b

[1, 2]

>>> 


查看完整回答
反對(duì) 回復(fù) 2019-05-20
  • 5 回答
  • 0 關(guān)注
  • 891 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)