python - 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' 是一个字符串,问题是通过它的浮点元素对元组进行排序
使用嵌套循环转置矩阵的程序
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.
解决方案
删除[
并]
拆分字符串:
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]
推荐阅读
- java - org.apache.jasper.JasperException:/WEB-INF/jsp/home.jsp(行:[159],列:[88])等号预期
- javascript - Javascript 更新 textContent
- android - Android:绑定到远程服务:崩溃服务
- firefox - 带有本机消息传递的 Firefox 包应用程序
- javafx - JavaFX - 将一行从 tableview 拖到 textarea
- terraform - 用于读取 JSON 文件的 GitHub Action
- python - Python:如何使用 matplotlib.image.imsave() 将精确的 numpy 数组数据保存到图像
- django - Django 3:将用户电子邮件设置为唯一的、最小的可行解决方案
- javascript - React:简单动画的 document.createElement 替代方案?
- python - 使用 spech_recognition 记下系统音频