【问题标题】:Python - How to print out all letters from a listPython - 如何打印出列表中的所有字母
【发布时间】:2016-10-30 01:50:53
【问题描述】:

有很多,我想打印出所有字母,无论是大写还是小写。我也不允许使用任何内置函数。我很难打印出字母列表。我得到的只是一个空的封闭括号。

alphabet = "abcdefghijklmnopqrstuvwxyz"

alphabet2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def get_symbols(lot):
list = []
for i in lot:
    if (i == alphabet or i == alphabet2):
        list.append(lot);
return list

给定的手数:

lot1 = [['.', '.', 'a', 'D', 'D'],
       ['.', '.', 'a', '.', '.'],
       ['A', 'A', '.', 'z', '.'],
       ['.', '.', '.', 'z', '.'],
       ['.', '.', 'C', 'C', 'C']]

我的输出:

Traceback (most recent call last):
File "tester4p.py", line 233, in test_get_symbols_2
def test_get_symbols_2 (self): self.assertEqual (get_symbols(lot1()),['a','D','A','z','C'])
AssertionError: Lists differ: [] != ['a', 'D', 'A', 'z', 'C']

Second list contains 5 additional elements.
First extra element 0:
'a'

- []
+ ['a', 'D', 'A', 'z', 'C']

预期输出:

['a', 'D', 'A', 'z', 'C']

【问题讨论】:

    标签: list function python-3.x if-statement for-loop


    【解决方案1】:

    我确信有更好的方法不涉及嵌套循环,但这是我会做的:

    alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    def get_symbols(lot):
        lst = []
        for chars in lot:
            for c in chars:
                if c in alphabets and c not in lst:
                    lst.append(c)
        return lst
    

    需要注意的几点:

    • 您应该避免使用 Python 使用的变量名称,例如 list
    • 如果i 是字符串'abc...'i == alphabet 只会是True,但如果i 是字符串'abc...' 中的任何字符,i in alphabet 将是True

    更新:

    试试这个变体来避免嵌套循环:

    alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    
    def get_symbols(lot):
        flat_lot = [item for sublist in lot for item in sublist]
        lst = []
        for c in flat_lot:
            if c in alphabets and c not in lst:
                lst.append(c)
        return lst
    

    【讨论】:

      【解决方案2】:

      将lot1展平,然后过滤掉字母

      lot1 = [['.', '.', 'a', 'D', 'D'],
             ['.', '.', 'a', '.', '.'],
             ['A', 'A', '.', 'z', '.'],
             ['.', '.', '.', 'z', '.'],
             ['.', '.', 'C', 'C', 'C']]
      
      import operator
      lot1 = reduce(operator.concat, lot1)
      lot1 = filter(str.isalpha, lot1)
      lot1 = list(set(lot1))
      lot1.sort()
      print lot1
      

      输出:

      ['A', 'C', 'D', 'a', 'z']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-14
        • 1970-01-01
        • 2017-09-04
        • 1970-01-01
        • 2019-04-18
        • 1970-01-01
        相关资源
        最近更新 更多