如何检查字符串是否可以转换为int,如果可以,请将其添加到列表中

时间:2018-10-24 12:11:32

标签: python

例如,我有一个列表:

l = ["z","u","k","h","r","a","1","2","3"]

我如何检查列表中的元素是否可以为int,如果可以,将其转换为int并替换列表中的str,这样我的列表看起来就像

l = ["z","u","k","h","r","a",1,2,3]

2 个答案:

答案 0 :(得分:2)

您可以为自己编写一个简单的函数,尝试将值转换为整数。

>>> def try_int(x):
...     try:
...         return int(x)
...     except ValueError:
...         return x
... 
>>> l = ["z","u","k","h","r","a","1","2","3"]
>>> [try_int(x) for x in l]
['z', 'u', 'k', 'h', 'r', 'a', 1, 2, 3]

遵循EAFP原则,我们只是尝试转换值x。这比对复杂的检查进行编码以找出是否可以转换要容易得多。

答案 1 :(得分:1)

您可以在转换前后使用ValueError块,而忽略for i, n in enumerate(l): try: l[i] = int(n) except ValueError: pass 例外:

  $args = array('hide_empty' => 0, 'orderby' => 'term_group');
  $terms = get_terms('category', $args);
  $hierarchy = _get_term_hierarchy('category');
  echo '<ul>';
  foreach ($terms as $term) {
    echo '<li>'.$term->name;
    if (array_key_exists($term->term_id, $hierarchy)) {
      echo '<ul>';
      foreach ($hierarchy[$term->term_id] as $v) {
        $child = get_term($v);
        echo '<li>'.$child->name.'</li>';
      }
      echo '</ul>';
    }
    echo '</li>';
  }
  echo '</ul>';