List Python-如何打印列表中的所有字母
有很多,我想打印出所有的字母,大写或小写。我也不允许使用任何内置函数。我很难打印出信件清单。我得到的回报是一个空的封闭括号List Python-如何打印列表中的所有字母,list,function,python-3.x,if-statement,for-loop,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.appen
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']
我确信有一种更好的方法不涉及嵌套循环,但我会这样做:
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
是字符串i
时才会为'abc…'
True,但如果
是字符串i
中的任何字符,则字母表中的'abc…'
i将为
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
我确信有一种更好的方法不涉及嵌套循环,但我会这样做:
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
是字符串i
时才会为'abc…'
True,但如果
是字符串i
中的任何字符,则字母表中的'abc…'
i将为
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
展平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']
展平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']