简体   繁体   English

Python元组而不是列表

[英]Python tuple instead of list

I read some tricks about Python and met the following code. 我阅读了有关Python的一些技巧,并遇到了以下代码。 I confused that why the code create tuple with two elements in the list insted of list. 我感到困惑的是,为什么代码在由list插入的list中创建具有两个元素的元组。 Why python returns tuple in list instead of list in list? 为什么python返回列表中的元组而不是列表中的列表? Is it related with are the tuples immutable? 它与元组不可变有关吗? Thanks in advance. 提前致谢。

>>>import os, glob
>>>[(os.stat(f).st_size, os.path.realpath(f)) for f in glob.glob('*.sh')]
[(3074, '/home/usr1/a.sh'),
(3386, '/home/usr1/b.sh'),
(3070, '/home/usr1/c.sh')]

The code explicitly generates tuples: 该代码显式生成元组:

(os.stat(f).st_size, os.path.realpath(f))

That's a 2-value tuple for each list element generated. 这是每个生成的列表元素的2值元组。 The list comprehension could be re-written as: 列表理解可以重写为:

result = []
for f in glob.glob('*.sh'):
    item = (os.stat(f).st_size, os.path.realpath(f))
    result.append(item)

Replace the parenthesis with square brackets if you wanted to generate nested lists: 如果要生成嵌套列表,请用方括号替换括号:

[[os.stat(f).st_size, os.path.realpath(f)] for f in glob.glob('*.sh')]

You create a tuple in Python by separating your items with commas: 通过用逗号分隔项目,可以在Python中创建一个元组:

>>> 1,2,3
(1, 2, 3)
>>> x = 1,2,3
>>> x
(1, 2, 3)

When using a list comprehension like you are, as well as other situations, you have to give python hints about the fact that you are trying to create a tuple (and it's tends to help other devs too, which is always a good thing). 当使用像您一样的列表理解以及其他情况时,您必须给python提示有关您正试图创建元组的事实(而且它也倾向于帮助其他开发人员,这总是一件好事)。 So as Martijin pointed out - (os.stat(f).st_size, os.path.realpath(f)) is creating a tuple. 因此,正如Martijin指出的那样- (os.stat(f).st_size, os.path.realpath(f))正在创建一个元组。

>>>[(os.stat(f).st_size, os.path.realpath(f)) for f in glob.glob('*.sh')]
    ^                  ^.                   ^
    |                    \_ this makes      |
    \__________________     it a tuple      |
                       \____________________\___ These are how Python knows to
that the comma makes it a tuple - they group that piece of code toegether.

You could put anything in there you want... 您可以在其中放置任何东西...

  • make it a list: [[os.stat(f).st_size, os.path.realpath(f)] for f in glob.glob('*.sh')] 列出: [[os.stat(f).st_size, os.path.realpath(f)] for f in glob.glob('*.sh')]
  • How about nothing? 没事吗 [None for f in glob.glob('*.sh')]
  • Let's take the filename backwards: [f[::1] for f in glob.glob('*.sh')] 让我们倒退文件名: [f[::1] for f in glob.glob('*.sh')]

This is a pretty advanced resource that talks about things like list comprehensions and generators that may be an interesting read. 是一个非常高级的资源,它讨论诸如列表推导和生成器之类的内容,这些内容可能很有趣。

(a,b) is a tuple. (a,b)是一个元组。 [(a,b)] is a list of tuples. [(a,b)]是一个元组列表。

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

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