[英]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 设为:
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_ 值设置为:
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.我并没有真正使用元组,所以我将 input_value 替换为列表,我希望它对你没问题。 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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.