简体   繁体   中英

Tuple values to list - having issues

Code I have so far:

def parse_measurement(input_value):
        split_list = input_value.split()
        try:
            split_list[0] = int(split_list[0])
        except ValueError:
            split_list[0] = float(split_list[0])
        return split_list
    input_text = "3 ft, 5 ft, 8.3 ft"
    output = [parse_measurement(s) for s in input_text.split(',')]
    print(output)

Now with the code above, if i put input_value as:

input_value = "3 ft, 5 ft, 8.3 ft"
output = [[3,'ft'], [5, 'ft'], [8.3, 'ft']]

How can I get the function fixed, so I can put the input_ value as:

input_value = ("3 ft", "5 ft", "8.3 ft") 

and still get the same output?

Thank you!

I don't really use tuple, so I replaced the input_value to list, I hope it's fine for you. The code:

input_value = ["3 ft", "5 ft", "8.3 ft"]
output = []
for i in range(len(input_value)):
    output.append(float(input_value[i].split()[0]))
print(output)

I reckon that it could be shortened a lot, so here is the shortened version:

input_value, output = ["3 ft", "5 ft", "8.3 ft"], []
for i in range(len(input_value)): output.append(float(input_value[i].split()[0]))
print(output)

Also, the output is float now, I didn't really find a way to fix that.

def parse_measurement(input_value):
    split_list = input_value.split()
    try: 
        split_list[0] = int(split_list[0])
    except:
        split_list[0] = float(split_list[0])
    return split_list

input_value = ("3 ft", "5 ft", "8.3 ft")
output = [parse_measurement(s) for s in input_text] # no split to divide string now
print(output)

Try this

def parse_entry(text):
    try:
        value, unit = text.split()
        return (float(value), unit)
    except:
        return (None, text)

def parse_measurement(input_value):
    return tuple([parse_entry(e) for e in input_value])
    

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