Python - 如何打印列表中的所有字母

时间:2016-10-30 01:50:53

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

有很多,我想打印出所有字母,无论是大写还是小写。我也不允许使用任何内置功能。我很难打印出来的信件清单。我得到的回报是一个空的封闭式支架。

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']

2 个答案:

答案 0 :(得分:0)

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

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 == alphabet是字符串True
  • i将只有'abc...',如果i in alphabet,则True将为i是字符串'abc...'
  • 中的任何字符

更新

尝试此变体以避免嵌套循环:

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

答案 1 :(得分:0)

展平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']