将两个列表放入字典,值为列表

2024-09-28 22:20:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个文件中读取如下字符串:

date,temperature
0101, 55
0101, 43
0101, 22
0102, 12
0102, 32
0103, 56
0104, 99

并将其转换为两个列表:

date = [0101, 0101, 0101, 0102, 0102, 0103, 0104]
temperature = [55, 43, 22, 12, 32, 56, 99]

我的最终目标是获得一个每天最高温度的输出,因此我认为第一步是创建一个字典,其中我将日期指定为关键字,温度指定为值:

datetemperature = {0101: [55,43,22], 0102: [12, 32], 0103: [56], 0104: [99]}

我试着迭代,但是我只得到一个温度值。Zip并没有真正起作用,因为我无法获得正确的温度和日期。有没有办法解决这个问题而不进口大熊猫或裸体动物

以下是我迄今为止所做的尝试,但是我发现很难理解我应该如何处理这个问题

  stations = []
days = []
temperatures = []

singledays = []
singlestations = []
singletemps = []

stationtemp = {}

for line in Lines:
    (station, day, ac, ad, af, ag, ah, aj, temp, al, ae, ar, at, ay, au, ai, alc, ap, ax, av, an) = line.strip().split(',')

stations.append(station)
days.append(day)
temperatures.append(temp)

for day in days: 
    if day in singledays:
        continue
    else:
        singledays.append(day)
        
for station in stations: 
    if station in singlestations:
        continue
    else:
        singlestations.append(station)
        
stationtemp = dict(zip(stations, temperatures))

Tags: infordateline温度daystemperaturestation
3条回答

每次遇到新日期时,只需添加一个键,如果已经添加了,则将其附加到现有键

假设温度是您的温度列表的名称,日期是您的日期列表,这应该可以:

fin_dict = dict()
for i in range(len(date)):
    if date[i] in fin_dict:
        fin_dict[date[i]].append(temperature[i])
    else:
        fin_dict[date[i]] = [temperature[i]]

使用simply nested for循环,您应该能够完成:

date = ['0101', '0101', '0101', '0102', '0102', '0103', '0104']
temperature = [55, 43, 22, 12, 32, 56, 99]
datetemperature = {}
for x in set(date): #this returns unique dates
    datetemperature[x] = [] #a list that holds all temperatures corresponding to a unique date 
    for k,v in enumerate(date): #runing a for loop on the enumerated date list, so as to keep track of the indices
        if v == x:
            datetemperature[x].append(temperature[k])

Output

{'0104': [99], '0101': [55, 43, 22], '0103': [56], '0102': [12, 32]}

这类作品:

weather = """
date,temperature
0101, 55
0101, 43
0101, 22
0102, 12
0102, 32
0103, 56
0104, 99
""".strip()

# Skip the first row
lines = weather.splitlines()[1:]

# Create a dictionary
# Iterate each line
# If the key doesn't exist, create one equal to empty list
# Otherwise, append temperature to list
# This also uses an interim dictionary (tmp).
out = {}
tmp = {}
for line in lines:
    d, t = line.replace(" ", "").split(",")
    if not d in tmp:
        tmp[d] = []
    tmp[d].append(t)
    out[d] = sorted(tmp[d], reverse=True)

结果:

{'0101': ['55', '43', '22'],
 '0102': ['32', '12'],
 '0103': ['56'],
 '0104': ['99']}

编辑:如果您只需要每天的最高温度,请根据给定键的当前值计算每个值

for line in lines:
    d, t = line.replace(" ", "").split(",")
    if d in out:
        if t > max(out[d]):
            out[d] = t
    else:
        out[d] = t

结果:

{'0101': '55',
 '0102': '32',
 '0103': '56',
 '0104': '99'}

相关问题 更多 >