简体   繁体   中英

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 = ['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.

The json library allows you to indent your dictionary-printing and makes it esier to read the output.

However, you could also use pandas.DataFrame to show the output as a table.

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:

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 : .

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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