如何在Python中找到列表的最大值?

2024-06-01 00:38:17 发布

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

我是Python初学者,列出了以下两个列表:

temp = [83, 384, 324.6, -234, -65, -65.838, 23, -85, -73.543, 12.345]
time = [0.0, 3.345, 4.785, 5.31, 6.67, 9.37, 10.54, 11.36, 12.554, 13.445]

我在玩火山模拟器,能够记录火山中某些点的温度。我把这些温度放在一个列表中,还把时间记录在一个列表中。我试图找到温度列表中的所有正值。 -----我想要的输出:

newtemp = [83, 384, 324.6, 23, 12.345]

Tags: 列表time记录时间模拟器温度temp初学者
2条回答

我想你要找的是这样的东西:

temp = [83, 384, 324.6, -234, -65, -65.838, 23, -85, -73.543, 12.345]
time = [0.0, 3.345, 4.785, 5.31, 6.67, 9.37, 10.54, 11.36, 12.554, 13.445]

max_temp = max(temp)
max_temp_position = temp.index(max_temp)
max_temp_time = time[max_temp_position]

print(max_temp, max_temp_time )

如果您使用字典列表,而不是我在上面的评论中提到的两个列表,那么这将变得更加容易和更好

[
  {temp:384, time:3.3},
  {temp:324, time:4,7}, 
  ...
]

编辑: 如果你想要局部极大值,那么温度的顺序很重要,而不是符号,但我会假设它只适用于下面的例子中的正局部极大值

例1:

def timeToLocalMax(time,temp):
    ans=[]
    for i in range(1,len(temp)-1):
      if temp[i]>temp[i+1] and temp[i]>temp[i-1] and temp[i]>0:
        ans.append((temp[i],time[i])) # you don't have to add both, you can do either also
        #like so ans.append(temp[i]) or ans.append(time[i])
    print(ans)
time=[0.0, 3.345, 4.785, 5.31, 6.67, 9.37, 10.54, 11.36, 12.554, 13.445]
temp=[83, 384, 324.6, -234, -65, -65.838, 23, -85, -73.543, 12.345]
timeToLocalMax(time,temp)

输出:

[(384, 3.345), (23, 10.54)]

[384, 23]

例2: 否则,如果您只需要temp的正值,可以这样做

ans=[i for i in temp if i>0]

然后,如果你想要对应于正值的时间,你可以这样做

ans=[time[i] for i in range(len(temp)) if temp[i]>0]

或者如果你想两者兼得,你会这么做

ans=[(time[i],temp[i]) for i in range(len(temp)) if temp[i]>0]

相关问题 更多 >