在Python中将列表转换为元组的时间复杂度,反之亦然 [英] Time complexity of casting lists to tuples in python and vice versa

查看:830
本文介绍了在Python中将列表转换为元组的时间复杂度,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将python列表转换为tuple(反之亦然)的时间复杂度:

  tuple 2,3,4,5,6,42])
list((10,9,8,7,6,5,4,3,1))



O(N)或O(1),即列表是否被复制或是从可写到内部切换到只读? >

非常感谢。

解决方案

tuple(list)只是将对象从列表复制到元组。 SO,你仍然可以修改内部对象(如果他们是可变的),但你不能添加新的项目到元组。



复制列表需要 O(N)时间。

 >>> tup =([1,2,3,4,5,6)
>>> [id(x)for x in tup]
[167320364,161878716,161878704,161878692]
>>> lis = list(tup)

内部对象仍指向相同的对象

 >>> [id(x)for x in lis] 
[167320364,161878716,161878704,161878692]

但是外容器现在是不同的对象。因此,修改外部对象不会影响其他对象。

 >> tup is lis 
False
>>> lis.append(10)
>>>> lup,tup
([[1,2,3,4,5,6,10],([1,2,3,3,4,5,6))#10未在tup $ b中添加$ b

修改可变内部对象将影响这两个容器:

 >>> tup [0] .append(100)
>>> tup [0],lis [0]
([1,2,3,100],[1,2,3,100])

时间比较建议列表复制和元组创建几乎相等的时间,但由于创建一个新的对象与新的属性,它的开销,因此元组创建稍贵。

 >>> lis = range(100)
>>>> %timeit lis [:]
1000000循环,最好的3:每循环1.22 usb
>>> %timeit tuple(lis)
1000000循环,最好的3:每个循环$ 1.7
>>> lis = range(10 ** 5)
>>>> %timeit lis [:]
100个循环,最好的3:每个循环2.66 ms
>>>> %timeit tuple(lis)
100循环,最好的3:每个循环2.77 ms


what is the time complexity of converting a python list to tuple (and vice versa):

tuple([1,2,3,4,5,6,42])
list((10,9,8,7,6,5,4,3,1))

O(N) or O(1), i.e. does the list get copied or is something somewhere internally switched from writable to read-only?

Thanks a lot!

解决方案

It is an O(N) operation, tuple(list) simply copies the objects from the list to the tuple. SO, you can still modify the internal objects(if they are mutable) but you can't add new items to the tuple.

Copying a list takes O(N) time.

>>> tup = ([1, 2, 3],4,5 ,6)
>>> [id(x) for x in tup]
[167320364, 161878716, 161878704, 161878692]
>>> lis = list(tup)

Internal object still refer to the same objects

>>> [id(x) for x in lis]
[167320364, 161878716, 161878704, 161878692]

But outer containers are now different objects. So, modifying the outer objects won't affect others.

>>> tup is lis
False
>>> lis.append(10)
>>> lis, tup
([[1, 2, 3], 4, 5, 6, 10], ([1, 2, 3], 4, 5, 6)) #10 not added in tup

Modifying a mutable internal object will affect both containers:

>>> tup[0].append(100)
>>> tup[0], lis[0]
([1, 2, 3, 100], [1, 2, 3, 100])

Timing comparison suggest list copying and tuple creation take almost equal time, but as creating a new object with new properties has it's overhead so tuple creation is slightly expensive.

>>> lis = range(100)
>>> %timeit lis[:]
1000000 loops, best of 3: 1.22 us per loop
>>> %timeit tuple(lis)
1000000 loops, best of 3: 1.7 us per loop
>>> lis = range(10**5)
>>> %timeit lis[:]
100 loops, best of 3: 2.66 ms per loop
>>> %timeit tuple(lis)
100 loops, best of 3: 2.77 ms per loop

这篇关于在Python中将列表转换为元组的时间复杂度,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆