【问题标题】:Is there a built in list in python or some package that has a list of the alphabet? [duplicate]python中是否有内置列表或某些包含字母列表的包? [复制]
【发布时间】:2013-11-13 20:38:43
【问题描述】:

python 中是否有内置列表或某些包含字母列表的包?我想避免这样的系统

alphabets = ('a','b','c',.....)

【问题讨论】:

  • 为什么我的问题被否决了?
  • 因为你显然没有用谷歌搜索它。
  • python alphabet 的第一个 google 结果是this question。第三个是string 模块的文档。

标签: python enumeration alphabetical


【解决方案1】:

使用string.ascii_lowercase:

>>> from string import ascii_lowercase
>>> ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> list(ascii_lowercase)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

【讨论】:

  • 为什么有人会否决这个答案?!? +1 我来补偿。请做同样的事情......
【解决方案2】:

你也可以做一个列表推导:

>>> [chr(i) for i in range(97,97+26)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

【讨论】:

  • 感谢您提供另一种实现方式。我是 Python 新手,还没有了解什么是列表推导,所以这有助于我理解列表推导和原始问题的答案,但我接受了另一个作为我的答案,因为它更易于维护和明白了,不过还是谢谢你! :)
  • @ArifAli:实际上,您为此选择了正确的答案作为“答案”。您应该优先使用ascii_lowercase 来生成这些常量。我只是将其作为替代方案。很高兴它对你有教育价值!
猜你喜欢
  • 2021-07-01
  • 2017-05-21
  • 2018-06-30
  • 2020-08-22
  • 2011-06-20
  • 2021-06-17
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
相关资源
最近更新 更多