Py学习  »  Python

hwo在python中从元组中提取数字和字符

jingchun liu • 2 年前 • 1003 次点击  

我有一个元组列表或字典如下。现在我想分别提取数字和字符(电子邮件)。

('a.fish@lancaster.ac.uk 14', 'aaronz@vt.edu 110', 'ajpoland@iupui.edu 48', 'antranig@caret.cam.ac.uk 18', 'arwhyte@umich.edu 27', 'bahollad@indiana.edu 4', 'bkirschn@umich.edu 27', 'chmaurer@iupui.edu 111',)


{'a.fish@lancaster.ac.uk': 14, 'aaronz@vt.edu': 110, 'ajpoland@iupui.edu':48, 'antranig@caret.cam.ac.uk': 18, 'arwhyte@umich.edu': 27, 'bahollad@indiana.edu': 4, 'bkirschn@umich.edu‘: 27, 'chmaurer@iupui.edu’: 111)

然后我想把max和email添加到一个字符串中。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133350
 
1003 次点击  
文章 [ 4 ]  |  最新文章 2 年前
Ram
Reply   •   1 楼
Ram    3 年前

你可以用 max() 如下图所示。

d ={'a.fish@lancaster.ac.uk': 14, 'aaronz@vt.edu': 110, 'ajpoland@iupui.edu':48, 'antranig@caret.cam.ac.uk': 18, 'arwhyte@umich.edu': 27, 'bahollad@indiana.edu': 4, 'bkirschn@umich.edu': 27, 'chmaurer@iupui.edu': 111}

x = max(d.items(), key= lambda y: y[1])
print(x)

这将给出最大数量和相关的电子邮件。

('chmaurer@iupui.edu', 111)
CodeWithAwais
Reply   •   2 楼
CodeWithAwais    3 年前

这里有一个解决方案

a_tuple = ('a.fish@lancaster.ac.uk 14', 'aaronz@vt.edu 110', 'ajpoland@iupui.edu 48', 'antranig@caret.cam.ac.uk 18', 'arwhyte@umich.edu 27', 'bahollad@indiana.edu 4', 'bkirschn@umich.edu 27', 'chmaurer@iupui.edu 111',)
a_dict = {'a.fish@lancaster.ac.uk': 14, 'aaronz@vt.edu': 110, 'ajpoland@iupui.edu':48, 'antranig@caret.cam.ac.uk': 18, 'arwhyte@umich.edu': 27, 'bahollad@indiana.edu': 4, 'bkirschn@umich.edu': 27, 'chmaurer@iupui.edu': 111}


print("***Tuple***\n")
for each in a_tuple:
    new = each.split(' ')

    for n in new:
        if n.isdigit():
            continue
        print(n)

print("\n***Dictionary***")

for keys in a_dict.keys():
    print(keys)
Prasanna P
Reply   •   3 楼
Prasanna P    3 年前
input_tuple = ('a.fish@lancaster.ac.uk 14', 'aaronz@vt.edu 110', 'ajpoland@iupui.edu 48', 'antranig@caret.cam.ac.uk 18', 'arwhyte@umich.edu 27', 'bahollad@indiana.edu 4', 'bkirschn@umich.edu 27', 'chmaurer@iupui.edu 111',)
dict = {}
for val in input_tuple:
    temp_val = val.split(' ')
    dict[temp_val[0]]=int(temp_val[1])
print (dict)

输出: {'aaronz@vt.edu': 110, 'ajpoland@iupui.edu': 48, 'bahollad@indiana.edu': 4, 'antranig@caret.cam.ac.uk': 18, 'chmaurer@iupui.edu': 111, 'arwhyte@umich.edu': 27, 'bkirschn@umich.edu“:27,”a。fish@lancaster.ac.uk': 14}

以上内容将有助于在python中从元组中提取数字和字符。

你能澄清一下“那么我想把max#和email添加到一个字符串中。”

user15801675 user15801675
Reply   •   4 楼
user15801675 user15801675    3 年前

这就是你想要的吗

d=('a.fish@lancaster.ac.uk 14', 'aaronz@vt.edu 110', 'ajpoland@iupui.edu 48', 'antranig@caret.cam.ac.uk 18', 'arwhyte@umich.edu 27', 'bahollad@indiana.edu 4', 'bkirschn@umich.edu 27', 'chmaurer@iupui.edu 111',)

dict1={i.split()[0]:int(i.split()[1]) for i in d}

print(max(dict1),dict1[max(dict1)])