Python 如何从以x开头的列表中提取单词
我想从列表中提取以每个字母表开头的所有单词。 我有以下代码,但它不适用于列表的列表Python 如何从以x开头的列表中提取单词,python,python-2.7,python-3.x,nested-lists,Python,Python 2.7,Python 3.x,Nested Lists,我想从列表中提取以每个字母表开头的所有单词。 我有以下代码,但它不适用于列表的列表 my_list= [['ARON', '0.1'], ['BEY', '0.2'], ['ABI', '0.05'], ['ZBBY', '0.9'], ['KB', '0.4']] result = [] for i in sorted_firstnames: if i[0] == 'a'.upper(): result.append(i) result 你可以试试这个 &
my_list= [['ARON', '0.1'], ['BEY', '0.2'], ['ABI', '0.05'], ['ZBBY', '0.9'], ['KB', '0.4']]
result = []
for i in sorted_firstnames:
if i[0] == 'a'.upper():
result.append(i)
result
你可以试试这个
>>> x = 'a'
>>> print([i for i in my_list if i[0][0].casefold() == x])
[['ARON', '0.1'], ['ABI', '0.05']]
如果你只需要一句话
>>> print([i[0] for i in my_list if i[0][0].casefold() == x])
['ARON', 'ABI']
您可以修改代码,如下所示,只获取以“A”开头的名称:
my_list= [['ARON', '0.1'], ['BEY', '0.2'], ['ABI', '0.05'], ['ZBBY', '0.9'], ['KB', '0.4']]
result = []
for i in my_list:
if i[0][0] == 'a'.upper():
result.append(i[0])
print(result)
结果是:
['ARON', 'ABI']
这是我的看法
my_list= [['ARON', '0.1'], ['BEY', '0.2'], ['ABI', '0.05'], ['ZBBY', '0.9'], ['KB', '0.4']]
alphabet = 'abcdefghijklmnopqrstuvtwxyz'
result = {k:[sublist[0] for sublist in my_list if sublist[0][0].lower() == k] for k in alphabet}
print(result) # prints: {'v': [], 'c': [], 'b': ['BEY'], 'o': [], ...}
active = {k:v for k,v in result.items() if v}
print(active) # prints: {'z': ['ZBBY'], 'b': ['BEY'], 'a': ['ARON', 'ABI'], 'k': ['KB']}
扫描每个字母并将结果放入result
。然后,它将在active
中隔离实际返回匹配项的字母
您可以将两个词典理解合并为一个,但结果不太可读。您可以使用
startswith
函数检查字符串的起始字母
请尝试以下代码:
my_list= [['ARON', '0.1'], ['BEY', '0.2'], ['ABI', '0.05'], ['ZBBY', '0.9'], ['KB', '0.4']]
result = []
for i in my_list:
if i[0].startswith('a'.upper()):
result.append(i[0])
print result
输出:
['ARON', 'ABI']
如有任何疑问,请告知我。请提供所需的样本输入输出。谢谢
如果我[0][0]。upper()==“A”
。你的str.upper():
走错了方向,缺少一个额外的索引