我是Python初学者,并列出了以下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]
我正在玩火山模拟器,并能够记录火山中某些位置的温度。我将这些温度放入列表中,并将时间记录在列表中。我正在尝试查找温度列表的所有正值。-----我想要的输出:
newtemp = [83, 384, 324.6, 23, 12.345]
使用zip()将两个列表的数据点合并为元组,使用生成器表达式从2元组列表中获取所有正数据点,使用zip()将2个元组的散列元组分离回元组,并使用带有列表的map从中获取列表:
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]
p_temp, p_time = map(list,zip( *(a for a in zip(temp,time) if a[0]>0) ))
print(p_temp)
print(p_time)
输出:
[83, 384, 324.6, 23, 12.345]
[0.0, 3.345, 4.785, 10.54, 13.445]
您可以在此处找到zip()
,map()
和list()
的说明:https://docs.python.org/3/library/functions.html
操作步骤会像这样明智地转换您的数据种类:
tmp1 = list(zip(temp,time))
tmp2 = list((a for a in tmp1 if a[0]>0))
tmp3 = list(zip( *tmp2 ))
print(tmp1)
print(tmp2)
print(tmp3)
print(*tmp3)
输出:#列表(zip(temp,time))[(83,0.0),(384,3.345),(324.6,4.785),(-234,5.31),(-65,6.67),(-65.838,9.37),(23,10.54),(-85,11.36),(-73.543,12.554),(12.345,13.445)]
# list((a for a in tmp1 if a[0]>0))
[(83, 0.0), (384, 3.345), (324.6, 4.785), (23, 10.54), (12.345, 13.445)]
# list(zip( *tmp2 ))
[(83, 384, 324.6, 23, 12.345), (0.0, 3.345, 4.785, 10.54, 13.445)]
# *list(zip( *tmp2 ))
(83, 384, 324.6, 23, 12.345) (0.0, 3.345, 4.785, 10.54, 13.445)
我认为您正在寻找的是这样的东西:
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 )
如果您使用词典列表而不是我在上面的评论中提到的2个列表,这将变得更加容易和更好。
[
{temp:384, time:3.3},
{temp:324, time:4,7},
...
]
编辑:好吧,如果您要使用局部极大值,那么温度的顺序很重要,而不是符号,但是仅在以下示例中,我将其假定为正局部极大值
Ex1:
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]
Ex2:否则,如果您只想要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]