简体   繁体   English

无需分配变量的Python列表

[英]Python lists without assigning variables

Well, I can easily use this code without errors on Python: 好吧,我可以轻松地在Python上使用此代码而不会出错:

>>>> a = range(5, 10)
>>>> b = range(15, 20)
>>>> a.extend(b)
>>>> a
[5, 6, 7, 8, 9, 15, 16, 17, 18, 19]

I also can use this method, without using b : 我也可以使用此方法,而无需使用b

>>>> a = range(5, 10)
>>>> a.extend(range(15, 20))
>>>> a
[5, 6, 7, 8, 9, 15, 16, 17, 18, 19]

But I can't figure out why the same thing doesn't happen in this case: 但是我不知道为什么在这种情况下不会发生相同的事情:

>>>> [5, 6, 7, 8, 9].extend(range(15, 20))
>>>>

Wasn't a supposed to be the same thing as the above list? 是不是a应该是同样的事情,上面的列表中? I only see as difference that I hardcoded the inicial state. 我仅将硬编码初始状态视为不同。 I could really understand that the hardcoded list cannot be modified while it's not in a variable or something but... 我真的很明白,硬编码列表不在变量或其他内容中时无法修改...

>>>> [5, 6, 7, 8, 9][2]
7

This surprises me. 这让我感到惊讶。 What is even more strange: 更奇怪的是:

>>>> [5, 6, 7, 8, 7].count(7)
2
>>>> [5, 6, 7, 8, 7].index(8)
3

Why can some list methods work on a hardcoded/not-in-a-variable list, while others can? 为什么有些列表方法可以在硬编码/非变量列表上工作,而其他方法可以呢?

I'm not really into using this, that's more for personal knowledge and understanding of the language than usefulness. 我并没有真正使用它,更多的是个人知识和对语言的理解,而不是有用。

  1. extend doesn't return a value. extend不返回值。 Thus, printing a.extend(b) will be None . 因此,打印a.extend(b)将为None Thus, if you have a = [5, 6, 7, 8, 9].extend(range(15, 20)) and print a it will show None . 因此,如果您有a = [5, 6, 7, 8, 9].extend(range(15, 20))并打印a ,它将显示None A way around it would be to concatenate lists a = [5, 6, 7, 8, 9] + range(15, 20) 一种解决方法是将列表a = [5, 6, 7, 8, 9] + range(15, 20)

  2. [5, 6, 7, 8, 9][2] - everything is as should be as it starts counting elements from 0. It is not modifying list, it is merely returning a certain element from the list. [5, 6, 7, 8, 9][2] -一切都应从开始从0开始计数元素。它不是在修改列表,而只是从列表中返回某个元素。

  3. [5, 6, 7, 8, 7].count(7) and [5, 6, 7, 8, 7].index(8) show the expected output. [5, 6, 7, 8, 7].count(7) [5, 6, 7, 8, 7].index(8) [5, 6, 7, 8, 7].count(7)[5, 6, 7, 8, 7].index(8)显示了预期的输出。 First one is the number of times 7 occurs in the list, second one is an index of number 8 (again, counting starts from 0). 第一个是列表中出现7的次数,第二个是数字8的索引(同样,计数从0开始)。

So, all in all the use of hardcoded list behaves as expected in all of the examples you've produced. 因此,所有使用硬编码列表的行为在您生成的所有示例中均符合预期。

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

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