如何在Python中创建字符列表

2024-05-06 01:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我的试题要求我把两个字母作为输入,并显示两个输入之间的字母表中的所有字母(包括)。它还需要按照用户输入它们的顺序(因此GA生成GFEDCBA,而不是ABCDEFG)。我将如何处理这项任务?


Tags: 用户顺序字母字母表gaabcdefg试题gfedcba
2条回答
>>> 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并得到这样的结果:

>>> letterList('m', 'N')
'mlkjihgfedcbaZYXWVUTSRQPON'

当您完全支持unicode时,谁需要ASCII?

>>> a = ' あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわを'
>>> letterList('し', 'ろ')
'しすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろ'

我真的不认为这值得回答,但正如@martineau在his comment中所说,在注释中放入这么多代码不是一个好主意。。。所以这里是:

>>> begin="A"
>>> end="G"
>>> print "%s" % list((chr(i) for i in range(ord(begin), ord(end) + 1 * (ord(end)-ord(begin))/abs(ord(end)-ord(begin)), (ord(end)-ord(begin))/abs(ord(end)-ord(begin))))) 
['A', 'B', 'C', 'D', 'E', 'F', 'G']
>>> begin="G"
>>> end="A"
>>> print "%s" % list((chr(i) for i in range(ord(begin), ord(end) + 1 * (ord(end)-ord(begin))/abs(ord(end)-ord(begin)), (ord(end)-ord(begin))/abs(ord(end)-ord(begin))))) 
['G', 'F', 'E', 'D', 'C', 'B', 'A']

唯一稍微相关的部分是chrord,以及(ord(end)-ord(begin))/abs(ord(end)-ord(begin))的“技巧”,即如果begin>;end则获取-1,尽管。。。

编辑:正如@martineau在another comment中指出的。。。你可以做一个更大的(!)一行并使用join获取字符串(而不是列表)。

>>> begin="G"
>>> end="A"
>>> print "".join((chr(i) for i in range(ord(begin), ord(end) + 1 * (ord(end)-ord(begin))/abs(ord(end)-ord(begin)), (ord(end)-ord(begin))/abs(ord(end)-ord(begin)))))
GFEDCBA

。。。这是一小段代码。。。:D

相关问题 更多 >