Is it possible to make a letter range in python?

前端 未结 8 1545
误落风尘
误落风尘 2021-01-02 17:23

Is there a way to do a letter range in python like this:

for x in range(a,h,)
相关标签:
8条回答
  • 2021-01-02 18:07

    Malcom's example works great, but there is a little problem due to how Pythons list comparison works. If 'A' to "Z" or some character to "ZZ" or "ZZZ" will cause incorrect iteration.

    Here "AA" < "Z" or "AAA" < "ZZ" will become false.

    In Python [0,0,0] is smaller than [1,1] when compared with "<" or ">" operator.

    So below line

    while len(start_int_list) < len(end_int_list) or start_int_list <= end_int_list:
    

    should be rewritten as below

    while len(start_int_list) < len(end_int_list) or\
            ( len(start_int_list) == len(end_int_list) and start_int_list <= end_int_list):
    

    It is well explained here https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types

    I rewrote the code example below.

    def strange(start, end_or_len, sequence='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
    
        seq_len = len(sequence)
        start_int_list = [sequence.find(c) for c in start]
        if isinstance(end_or_len, int):
            inclusive = True
            end_int_list = list(start_int_list)
            i = len(end_int_list) - 1
            end_int_list[i] += end_or_len - 1
            while end_int_list[i] >= seq_len:
                j = end_int_list[i] // seq_len
                end_int_list[i] = end_int_list[i] % seq_len
                if i == 0:
                    end_int_list.insert(0, j-1)
                else:
                    i -= 1
                    end_int_list[i] += j
        else:
            end_int_list = [sequence.find(c) for c in end_or_len]
    
        while len(start_int_list) < len(end_int_list) or\
             (len(start_int_list) == len(end_int_list) and start_int_list <= end_int_list):**
            yield ''.join([sequence[i] for i in start_int_list])
            i = len(start_int_list)-1
            start_int_list[i] += 1
            while start_int_list[i] >= seq_len:
                start_int_list[i] = 0
                if i == 0:
                    start_int_list.insert(0,0)
                else:
                   i -= 1
                    start_int_list[i] += 1
    

    Anyway, Malcom's code example is a great illustration of how iterator in Python works.

    0 讨论(0)
  • 2021-01-02 18:10

    this is easier for me at least to read/understand (and you can easily customize which letters are included, and in what order):

    letters = 'abcdefghijklmnopqrstuvwxyz'
    for each in letters:
        print each
    
    result:
    a
    b
    c
    ...
    z
    
    0 讨论(0)
提交回复
热议问题