2017-09-27 90 views
1

我需要采取列表中的所有值,如果它们是字符串或它们的实际数字(如果它们是int),则将它们替换为零。 w.replace是我将如何替换字符串,但我不知道用什么来替换0。如何检查列表中的值是否是字符串?

def safe_int(list): 

list = [w.replace(, "0") for w in list] 
list = [int(i) for i in list] 

我想在list_of_strings里面用零替换“a”,把零“zebra”的全部替换为零。

list_of_strings = ["a", "2", "7", "zebra" ] 

最终输出应为[0,2,7,0]

+0

'list = [0如果isinstance(w,str)else int(w)for w in list_of_strings]'? – scnerd

+0

@scnerd他们都将成为字符串,只是一些将字符串与数字字符。 –

回答

3

可以尝试使用string_isdigit

list_of_strings = ["a", "2", "7", "zebra" ] 
[int(x) if x.isdigit() else 0 for x in list_of_strings] 
+0

这工作非常好,谢谢:D –

+0

请参阅[Python文档](https://docs.python.org/3/library/stdtypes.html#str.isdigit) –

1

可以使用尝试/捕获解析int,例如像这样:

def safe_list(input_list): 
    # initialize an output list 
    output_list = [] 

    # iterate through input list 
    for value in input_list: 
     try: 
      # try to parse value as int 
      parsed = int(value) 
     except ValueError: 
      # if it fails, append 0 to output list 
      output_list.append(0) 
     else: 
      # if it succeeds, append the parsed value (an int) to 
      # the output list. 
      # note: this could also be done inside the `try` block, 
      # but putting the "non-throwing" statements which follow 
      # inside an else block is considered good practice 
      output_list.append(parsed) 

    return output_list 
相关问题