简体   繁体   English

python中这两个表达式有区别吗

[英]Is there a difference between these two expressions in python

So, basically I just started learning python and I can't find something that proves if these two instructions do the same thing or not I have two lists and I want to copy one into another, the thing is that I do not understood if this instruction is right所以,基本上我刚开始学习 python,我找不到可以证明这两条指令是否做同样事情的东西我有两个列表,我想将一个复制到另一个列表中,问题是我不明白这是否指令是对的
newList = [x[:] for x in List] because newList = List does the same thing Is there a difference between these two instructions? newList = [x[:] for x in List]因为newList = List做同样的事情 这两条指令有区别吗? Thanks!谢谢!

In the first cursory look they look essentially same but there could be a difference if the List is not a list of lists [as is immediately understood by its name] ..if List is actually a tuple of tuples (supposing a naming mistake .. :-)) or something else.乍一看,它们看起来基本相同,但如果 List 不是列表列表 [正如其名称立即理解的那样] ..如果 List 实际上是元组的元组(假设命名错误.. :-)) 或者是其他东西。 In such a case you are creating a list of tuples (by the first command) from what was initially something else.在这种情况下,您正在从最初的其他内容创建元组列表(通过第一个命令)。 Other such possibilities also exist.其他这样的可能性也存在。 So please see the print and type of NewList and List carefully.所以请仔细查看NewList 和List 的打印和类型。 A subtle difference and they are not same.一个细微的区别,它们并不相同。

You might be actually doing a type conversion if you are following the first command.如果您遵循第一个命令,您实际上可能正在执行类型转换。

Consider the code below.考虑下面的代码。

List = tuple( (x,x+1) for x in range(10))
newList = [x[:] for x in List]

The output of print and type reveal the difference instantly.打印和类型的输出立即显示差异。

print(List)
print(newList)
type(List)
type(newList)

respective Outputs各自的输出

((0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
<class 'tuple'>
<class 'list'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM