简体   繁体   English

如何从字符串列表中提取整数以创建公式?

[英]How can I extract integers from a list of strings to create a formula?

timeList = ['7m:13s', '11m:29s', '16m:48s', '3m:26s', '120m:0s']

How can I take the minutes and seconds from this list?我怎样才能从这个列表中取出分钟和秒? I want to be able to create a formula to calculate miles per hour.我希望能够创建一个公式来计算每小时英里数。

Iterate through the timeList and extract minute and second portion from it and convert it into integer for further process.遍历 timeList 并从中提取分钟和秒部分并将其转换为整数以供进一步处理。

timeList = ['7m:13s', '11m:29s', '16m:48s', '3m:26s', '120m:0s']
for element in timeList:
    min = int(str(element).split(":")[0].split("m")[0])
    sec = int(str(element).split(":")[1].split("s")[0])
    print(min,sec)

Solution解决方案

You can slice the two parts using str('7m:13s').split(':') and then process the minute and seconds parts separately as I have shown below.您可以使用str('7m:13s').split(':')对两个部分进行切片,然后分别处理分钟和秒部分,如下所示。

The json library allows you to indent your dictionary-printing and makes it esier to read the output. json库允许您缩进字典打印并使其更容易阅读输出。

However, you could also use pandas.DataFrame to show the output as a table.但是,您也可以使用pandas.DataFrame将输出显示为表格。

Since, you mentioned about calculating speed, let me make some dummy data for distance traveled (in miles) and use it to calculate speed (in miles/hour).因为,你提到了计算速度,让我为行驶距离(以英里为单位)制作一些虚拟数据,并用它来计算速度(以英里/小时为单位)。

distances = ['0.5', '1.2', '3.8', '10.0', '100.0']

The solution below calculates the time in hours and evaluates the speed as well.下面的解决方案以小时为单位计算时间并评估速度。

Code代码

import json
import pandas as pd

timeList = ['7m:13s', '11m:29s', '16m:48s', '3m:26s', '120m:0s']

# dummy data for distance (in miles)
distances = ['0.5', '1.2', '3.8', '10.0', '100.0']

# We will save the time-spans in a
# dictionary post-processing
time_spans = dict()

for i, (ts, distance) in enumerate(zip(timeList, distances)):
    tmin, tsec = ts.split(':')
    time_spans.update({i: {'distance': float(distance),
                           'timespan': ts,
                           'minutes': int(tmin[:-1]),
                           'seconds': int(tsec[:-1]),
                           }})
# Print the dictionary (uncomment if necessary)
#print(json.dumps(time_spans, indent=2))

# Print DataFrame: As a table
df = pd.DataFrame(time_spans).T
# Calculate elapsed time (in hours)
df['time'] = df['minutes']/60 + df['seconds']/(60*60)
# Calculate speed: distance/time (in miles/hour)
df['speed'] = df['distance']/df['time']

print(df)

Pandas DataFrame :熊猫数据帧

  distance timespan minutes seconds       time    speed
0      0.5   7m:13s       7      13   0.120278  4.15704
1      1.2  11m:29s      11      29   0.191389  6.26996
2      3.8  16m:48s      16      48       0.28  13.5714
3       10   3m:26s       3      26  0.0572222  174.757
4      100  120m:0s     120       0          2       50

If you want to compute speeds based on time, you will need a distance.如果您想根据时间计算速度,则需要一个距离。 If you want this to be in miles per hours, you'll want to convert these times to a number (or fraction) of hours.如果您希望以每小时英里数为单位,您需要将这些时间转换为小时数(或分数)。 this can be done in a list comprehension:这可以在列表理解中完成:

timeList = ['7m:13s', '11m:29s', '16m:48s', '3m:26s', '120m:0s']

# converting to hours
hours = [(m*60+s)/3600 for ms in timeList for m,s in [map(int,ms[:-1].split("m:"))]]

#computing speeds:
distance = 1 # mile
mph      = [distance/time for time in hours]

print(mph)

# [8.314087759815243, 5.2249637155297535, 3.571428571428571, 17.475728155339805, 0.5]

if your distances are in a matching list, you can get the speed for each entry by using zip:如果您的距离在匹配列表中,您可以使用 zip 获取每个条目的速度:

miles = [ 10, 5, 8, 9 ]
mph   = [distance/time for distance,time in zip(miles,hours)]

# [83.14087759815243, 26.124818577648767, 28.57142857142857, 157.28155339805826]

you could combine the two into a single line but it would be ugly and hard to maintain:您可以将两者合并为一行,但这会很丑陋且难以维护:

mph = [distance*3600/(m*60+s) for distance,ms in zip(miles,timeList) for m,s in [map(int,ms[:-1].split("m:"))]]

Remove m and s from each item then split on : .从每个项目中删除ms然后拆分:

timeList = ['7m:13s', '11m:29s', '16m:48s', '3m:26s', '120m:0s']

for item in timeList:
    minutes, seconds = item.replace('m', '').replace('s', '').split(':')
    minutes, seconds = int(minutes), int(seconds)
    print(minutes, seconds)

Output:输出:

7 13
11 29
16 48
3 26
120 0

Update:更新:

I am a complete beginner in python, if that wasn't clear.如果不清楚的话,我是一个完整的 Python 初学者。

I wanted to use list comprehension and keep all of my methods and assignments in one line, but it made it difficult for me to comprehend.我想使用列表理解并将我所有的方法和作业放在一行中,但这让我很难理解。 My final code went step by step through through the process.我的最终代码逐步完成了整个过程。 Probably not the most efficient way, but I was able to figure it out.可能不是最有效的方法,但我能够弄清楚。

I used slicing, strip and split to get my numbers out of the string, then converted each to their needed units.我使用切片、剥离和拆分将我的数字从字符串中取出,然后将每个数字转换为所需的单位。

distanceList = [0.04, 0.05, 0.91, 0.16, 18]
timeList = ['7m:13s', '11m:29s', '16m:48s', '3m:26s', '120m:0s']


zipList = zip(distanceList, timeList)
for i in zipList:
    distance = i[0]
    time = i[1]
    numbers = time.split("m:")
    minute = numbers[0]
    sec = numbers[1].strip("s")
    hoursmin = (float(minute) / 60)
    hourssec = (float(sec) / 3600)
    hours = (hoursmin + hourssec)
    mph = (distance / hours)
    print("Distance: ", distance, "Time: ", time, "Speed: ", round(mph, 2), "miles/hr")

output:输出:

('Distance: ', 0.04, 'Time: ', '7m:13s', 'Speed: ', 0.33, 'miles/hr')
('Distance: ', 0.05, 'Time: ', '11m:29s', 'Speed: ', 0.26, 'miles/hr')
('Distance: ', 0.91, 'Time: ', '16m:48s', 'Speed: ', 3.25, 'miles/hr')
('Distance: ', 0.16, 'Time: ', '3m:26s', 'Speed: ', 2.8, 'miles/hr')
('Distance: ', 18, 'Time: ', '120m:0s', 'Speed: ', 9.0, 'miles/hr')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM