首页 > 解决方案 > TypeError:并非所有参数都在字符串格式化期间转换(Python 3)(字符串)

问题描述

我在 Python 3 上收到此错误TypeError: not all arguments converted during string formatting,我知道这是由于字符串以“ [”开头,但我要解决的问题是将其作为输入字符串 ' [1, 2, 3, 4, 5, 6, 7, 8, 9]',任务是在 Python 3 上查找偶数。任何帮助将非常感激。

def is_even_num(l):
  enum = []
  for n in l:
     if n % 2 == 0:
       enum.append(n)
  return enum
print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))

**TypeError: not all arguments converted during string formatting**
If I try int(n), I get this error **ValueError: invalid literal for int() with base 10: '[' ** 

编辑1:

由于输入是字符串,我面临类似的问题

Python 练习:按元组的浮点元素对元组进行排序

price = "[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]" 
print( sorted(price, key=lambda x: float(x[1]), reverse=True)) 
IndexError: string index out of range 

这里 'Price' 是一个字符串,问题是通过它的浮点元素对元组进行排序

  1. 使用嵌套循环转置矩阵的程序

    y = "[[1,2,3,4],[4,5,6,7]]"
    result = [[0,0],
     [0,0],
     [0,0],
     [0,0]]
    
    #iterate through rows
    for i in range(len(X)):
    # iterate through columns
        for j in range(len(X[0])):
            result[j][i] = X[i][j]
    for r in result:
      print(r)
    
     IndexError: list index out of range ` I am getting this same type of problem again, the matrix has been input as a STRING.
    

标签: pythonpython-3.xstringruntime-error

解决方案


删除[]拆分字符串:

def is_even_num(l):
  enum = []
  for n in l.replace('[','').replace(']','').split(', '):
    if int(n) % 2 == 0:
       enum.append(n)
  return enum
print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))

输出:

['2', '4', '6', '8']

另一种优雅的方法是使用ast

def is_even_num(l):
  enum = []
  for n in ast.literal_eval(l):
    if int(n) % 2 == 0:
       enum.append(n)
  return enum
print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))

输出:

['2', '4', '6', '8']

同样对于您问题的第二部分,如前所述,只需使用ast

price = "[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]"  
price = ast.literal_eval(price) 
print( sorted(price, key=lambda x: float(x[1]), reverse=True))

输出:

[('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]

然后:

y = "[[1,2,3,4],[4,5,6,7]]"
result = [[0,0],
 [0,0],
 [0,0],
 [0,0]]
X = ast.literal_eval(y)
#iterate through rows
for i in range(len(X)):
# iterate through columns
    for j in range(len(X[0])):
        result[j][i] = X[i][j]
for r in result:
  print(r)

输出:

[1, 4]
[2, 5]
[3, 6]
[4, 7]

推荐阅读