在python中将输入的字符串转换为列表

2024-04-20 04:05:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的应用程序中,用户输入数据,然后用于计算

例如,输入的数据是:

[[74,74],[65,73],[91,69]]

当然,当尝试打印(type(data))时,我得到的是字符串类型

我遍历这些数组,所以我需要它是列表类型

我尝试使用split/eval,但没有成功

#Enter text_to_decipher
  print("Enter your text to decipher or keep the default: ")
  print(text_to_decipher)
  print('\n')

  #start collecting input
  temp_text = ""
  while True:
    temp=input()
    if temp == "":
      break
    else:
      temp_text = temp_text + temp 

  if temp_text != "":
      text_to_decipher = temp_text
  print (text_to_decipher)
  print (type(text_to_decipher))

  text_to_decipher = input()
  print (type(text_to_decipher))

代码尝试遍历字符串而不是列表时发生的错误:

Traceback (most recent call last): File "main.py", line 1091, i <module ats1=iter(pair,k[2],iter_function) file "main.py", line 1022, in iter r=M[1] IndexError: string index out of range

有什么想法吗


Tags: to数据字符串text类型列表inputif
1条回答
网友
1楼 · 发布于 2024-04-20 04:05:16

您可以使用ast.literal_eval

import ast

str_data = '[[74, 74], [65, 73], [91, 69]]'
data = ast.literal_eval(str_data)
print(type(data), data)
# <class 'list'> [[74, 74], [65, 73], [91, 69]]

相关问题 更多 >