2017-09-27 13 views
1

リスト内のすべての値を取って、文字列の場合は0に、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内部ゼロと「シマウマ」の全体を交換したいです。

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

エンド出力はあなたがたとえば、int型を解析するためにキャッチ/試みる使用することができますstring_isdigit

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

'list = [0 if isinstance(w、str)else int(w)for list_of_strings]'? – scnerd

+0

@scnerdそれらはすべて文字列になります。ちょうどいくつかは数字文字列です。 –

答えて

3

する必要があります

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 
+0

これは非常にうまくいきました。D –

+0

[Python docs](https://docs.python.org/3/library/stdtypes.html#str.isdigit)も参照してください。 –

1

を使用しようとすることができ、[0、2、7、0]

関連する問題