有很多,我想打印出所有字母,无论是大写还是小写。我也不允许使用任何内置功能。我很难打印出来的信件清单。我得到的回报是一个空的封闭式支架。
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']
答案 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
有几点需要注意:
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']