我有一个包含字符串的列表。有些字符串包含字母,有些包含数字。我想将其中带有数字的字符串之一转换为浮点数,但出现错误
该列表称为#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int level = 1;
char const offsets[] = "\t\t\t\t\t\t\t\t";
pid_t create_child_process(int(*child_fn)()) {
// Flush the output buffers to avoid duplicate output from the child process.
fflush(stdout);
fflush(stderr);
pid_t child_pid = fork();
switch(child_pid) {
case 0: // Child process.
++level;
exit(child_fn());
case -1: // fork() failed.
abort();
default: // Parent process.
printf("%.*s %u spawned %u\n", level, offsets, (unsigned)getpid(), (unsigned)child_pid);
return child_pid;
}
}
void wait_for_any_child() {
int wstatus;
pid_t child_pid = wait(&wstatus);
if(child_pid == -1)
abort();
printf("%.*s %u terminated\n", level, offsets, (unsigned)child_pid);
}
int p2() { return 0; }
int p5() { return 0; }
int p6() { return 0; }
int p7() { return 0; }
int p4() {
create_child_process(p5);
create_child_process(p6);
create_child_process(p7);
wait_for_any_child();
wait_for_any_child();
wait_for_any_child();
return 0;
}
int p3() {
create_child_process(p4);
wait_for_any_child();
return 0;
}
int p1() {
printf("%u started\n", (unsigned)getpid());
create_child_process(p2);
create_child_process(p3);
wait_for_any_child();
wait_for_any_child();
printf("%u terminated\n", (unsigned)getpid());
return 0;
}
int main() {
return p1();
}
。列表的第三个元素是数字。我尝试了5962 started
5962 spawned 5963
5962 spawned 5964
5963 terminated
5964 spawned 5965
5965 spawned 5966
5965 spawned 5967
5965 spawned 5968
5966 terminated
5967 terminated
5968 terminated
5965 terminated
5964 terminated
5962 terminated
,但它给了我x
请参阅我将x[2] = float (x[2])
与:Value error: could not convert string to a float:%"
float(x[2])
答案 0 :(得分:0)
在您的if
语句周围,您可以包装一个try/except
块,程序将try
将float(x[2])
转换为浮点数,但是如果不能(因为它是字符串) ),它将执行代码的except
部分。
try:
if float(x[2]) > 50.0:
print('got one')
except:
# do something else, if x[2] is not a float
pass # if you don't want to do anything.
答案 1 :(得分:0)
您可以使用正则表达式检查它是否为数字,然后可以安全地将其强制转换为浮点数。
Events