>>> import string
>>> def letterList (start, end):
# add a character at the beginning so str.index won't return 0 for `A`
a = ' ' + string.ascii_uppercase
# if start > end, then start from the back
direction = 1 if start < end else -1
# Get the substring of the alphabet:
# The `+ direction` makes sure that the end character is inclusive; we
# always need to go one *further*, so when starting from the back, we
# need to substract one. Here comes also the effect from the modified
# alphabet. For `A` the normal alphabet would return `0` so we would
# have `-1` making the range fail. So we add a blank character to make
# sure that `A` yields `1-1=0` instead. As we use the indexes dynamically
# it does not matter that we have changed the alphabet before.
return a[a.index(start):a.index(end) + direction:direction]
>>> letterList('A', 'G')
'ABCDEFG'
>>> letterList('G', 'A')
'GFEDCBA'
>>> letterList('A', 'A')
'A'
请注意,此解决方案允许使用任何类型的字母表。我们可以设置
a = ' ' + string.ascii_uppercase + string.ascii_lowercase
并得到这样的结果:当您完全支持unicode时,谁需要ASCII?
我真的不认为这值得回答,但正如@martineau在his comment中所说,在注释中放入这么多代码不是一个好主意。。。所以这里是:
唯一稍微相关的部分是chr和ord,以及
(ord(end)-ord(begin))/abs(ord(end)-ord(begin))
的“技巧”,即如果begin>;end则获取-1,尽管。。。编辑:正如@martineau在another comment中指出的。。。你可以做一个更大的(!)一行并使用join获取字符串(而不是列表)。
。。。这是一小段代码。。。:D
相关问题 更多 >
编程相关推荐