提问人:angeliquelinde 提问时间:12/28/2022 最后编辑:Nikolaj Š.angeliquelinde 更新时间:1/3/2023 访问量:140
解析字符串列表并查找最大值
Parse list of strings and find max values
问:
我对 Python 很陌生,正在努力弄清楚这个 for 循环中的逻辑。我的数据有两个值,一个城市和一个临时。我想写一个“for 循环”,输出每个城市的最大温度,如下所示:
PAR 31
LON 23
RIO 36
DUB 44
由于要在Hadoop中使用,因此我不能使用任何python库。
这是我的数据集:
['PAR,31',
'PAR,18',
'PAR,14',
'PAR,18',
'LON,12',
'LON,13',
'LON,9',
'LON,23',
'LON,5',
'RIO,36',
'RIO,33',
'RIO,21',
'RIO,25',
'DUB,44',
'DUB,42',
'DUB,38',
'DUB,34']
这是我的代码:
current_city = None
current_max = 0
for line in lines:
(city, temp) = line.split(',')
temp = int(temp)
if city == current_city:
if current_max < temp:
current_max == temp
current_city = city
print(current_city, current_max)
这是我的输出:
DUB 0
答:
1赞
Lost_coder
12/28/2022
#1
您可以遍历您的列表。分离您的数据。检查城市是否已经在字典中。如果是这样,请检查温度是否高于保存在字典中的温度,如果是这种情况,请替换字典中的条目。
如果该城市不在字典中,只需将其添加到字典中即可。
a = ['PAR,31',
'PAR,18',
'PAR,14',
'PAR,18',
'LON,12',
'LON,13',
'LON,9',
'LON,23',
'LON,5',
'RIO,36',
'RIO,33',
'RIO,21',
'RIO,25',
'DUB,44',
'DUB,42',
'DUB,38',
'DUB,34']
dict = {}
for entry in a:
city,temp = entry.split(",")
if city in dict.keys():
if dict[city] < int(temp):
dict[city] = int(temp)
else:
dict[city] = int(temp)
print(dict)
输出:
{'PAR': 31, 'LON': 23, 'RIO': 36, 'DUB': 44}
0赞
Codist
12/28/2022
#2
建立一个以城市名称为键的词典。关联的值应为整数(温度)列表。
构建字典后,您可以遍历其项目以确定每个温度列表中的最高值,
data = ['PAR,31',
'PAR,18',
'PAR,14',
'PAR,18',
'LON,12',
'LON,13',
'LON,9',
'LON,23',
'LON,5',
'RIO,36',
'RIO,33',
'RIO,21',
'RIO,25',
'DUB,44',
'DUB,42',
'DUB,38',
'DUB,34']
d = {}
for e in data:
city, temp = e.split(',')
d.setdefault(city, []).append(temp)
for k, v in d.items():
print(k, max(map(int, v)))
输出:
PAR 31
LON 23
RIO 36
DUB 44
0赞
Nikolaj Š.
12/28/2022
#3
鉴于这里的答案有点啰嗦......
result = {}
for city, t in (l.split(',') for l in lines):
t = int(t)
result[city] = max(result.setdefault(city, t), t)
# you can print result however you like, e.g.:
for c, t in result.items():
print(f"{c} {t}")
如果您想牺牲一点可读性来提升 ~30% 的性能,请自己比较值,而不是调用:max
for city, t in (l.split(',') for l in lines):
t = int(t)
old_t = result.setdefault(city, t)
result[city] = old_t if old_t > t else t
评论
{city: max_temp}
dict.setdefault
dict.get