【问题标题】:Python comprehension and data structures [closed]Python理解和数据结构[关闭]
【发布时间】:2016-02-10 10:32:00
【问题描述】:

我正在学习一些python,并且我有以下程序:

sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()

print "\n What the hell is this???"
word_lengths = [(word, len(word)) for word in words if word != "the".lower()]
print word_lengths

What the hell is this???
[('quick', 5), ('brown', 5), ('fox', 3), ('jumps', 5), ('over', 4), ('lazy', 4), ('dog', 3)]

我不明白后一个代码块得到的奇怪列表..

它是什么样的结构?

提前致谢!

【问题讨论】:

  • 这是一个元组列表。有什么问题?
  • 您可以阅读有关元组和序列的信息here
  • 谢谢大家,这正是我需要的!
  • 一个简短问题的相当长的代码。

标签: python list-comprehension dictionary-comprehension


【解决方案1】:

它是一个元组列表。元组只是一个不可变列表,形式为x, y, z(x, y, z)

当您调用此代码时:

word_lengths = [(word, len(word)) for word in words if word != "the".lower()]

你要求 Python 制作一个包含元组 (x, y) 的列表 [a, b],其中 x 是单词,y 是单词的长度。

它在语义上几乎等同于:

word_lengths = [[word, len(word)] for word in words if word != "the".lower()]

唯一的例外是一旦创建元组就不能修改。

注意:要创建1个元素的元组,需要在括号之间添加逗号来区分表达式:(a,)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2018-12-22
    相关资源
    最近更新 更多