Python 输入验证并将元组列表转换为txt文件
我正在尝试将元组列表转换为txt文件,并对两个输入进行输入验证。顺便说一句,我试图做它没有和CSV模块。 我得到了这个元组列表:Python 输入验证并将元组列表转换为txt文件,python,list,tuples,export,Python,List,Tuples,Export,我正在尝试将元组列表转换为txt文件,并对两个输入进行输入验证。顺便说一句,我试图做它没有和CSV模块。 我得到了这个元组列表: list1 = [(16, 'Peter' , 2005) , (21, 'Philip', 2000) , (10, 'Kate', 2011)] 我想把它转换成一个txt文件,如下所示: Age Name YOB 16 Peter 2005 21 Philip 2000 10 Kate 20
list1 = [(16, 'Peter' , 2005) , (21, 'Philip', 2000) , (10, 'Kate', 2011)]
我想把它转换成一个txt文件,如下所示:
Age Name YOB
16 Peter 2005
21 Philip 2000
10 Kate 2011
我需要对输入进行验证,确认第一个输入是一个列表,第二个输入是一个字符串。文件行应该用制表符分隔
def my_func(list1,new_file):
header = "Age, Name, YOB"
if isinstance(list1, list):
for i in list1:
if isinstance(list1[i], str):
with open("Age_file.txt", "w") as output:
output.write(header + "\n")
output.close()
with open("Age_file.txt", "w") as output:
for i in output:
output.write(str(i) + "\n")
else:
"Second input must be a str."
else:
"First input must be a list."
但我得到这个类型错误:
'''
if isinstance(list1[i], str):
TypeError: list indices must be integers or slices, not tuple
'''
谢谢你的帮助,谢谢 这里的问题是,第二个
for
循环中的i
是一个元组,如回溯中所述。实际上,您正在尝试执行以下操作,以避免出现错误:
list1[(16, 'Peter' , 2005)]
听起来您希望确保每个元组的第二项是str
,在这种情况下,您的代码应该如下所示。我还对其进行了修改,使您只打开一次文件,而不是每次迭代都打开一次,然后继续使用new_file
param,您似乎根本没有使用它
def my_func(list1, new_file):
if not isinstance(list1, list):
raise ValueError("First argument must be a list!")
header = "Age, Name, YOB"
with open(new_file, "w") as output:
output.write(header + "\n")
for line in list1:
if not isinstance(line[1], str):
raise ValueError("Second item in each tuple must be a str!")
vals = ",".join(str(i) for i in line)
output.write(vals + "\n")
你有没有试着做三个独立的元组列表?然后你只有一个字符串列表和两个数字列表。。。然后你可以把:
list1 = [16, 21, 10]
list2 = ['Peter', 'Philipp', 'Kate']
list3 = [2005, 2000, 2010]
listfull = list(zip(list1, list2, list3))
然后您可以从这些列表中创建一个数据帧:
df = pd.DataFrame(listfull, columns =['Age', 'Name', 'YOB'])
然后你可以将其作为文本或csv文件保存。。。
我不确定这是否有帮助
df.to_csv('df.csv')
下面的评论中提到了代码失败的原因:
list1 = [(16, 'Peter' , 2005) , (21, 'Philip', 2000) , (10, 'Kate', 2011)]
# list1 is a list of tuples here
def my_func(list1,new_file):
#assuming we are getting same list1 defined above list1 is still list of tuples
header = "Age, Name, YOB"
if isinstance(list1, list):
for i in list1:
# i should be tuples like (16, 'Peter' , 2005)
if isinstance(list1[i], str): # error thrown because i is tuple
with open("Age_file.txt", "w") as output:
output.write(header + "\n")
output.close()
with open("Age_file.txt", "w") as output:
for i in output:
output.write(str(i) + "\n")
else:
"Second input must be a str."
else:
"First input must be a list."
您可以尝试以下代码:
list1 = [(16, 'Peter' , 2005) , (21, 'Philip', 2000) , (10, 'Kate', 2011)]
# list1 is a list of tuples here
def my_func(list1,new_file):
if not isinstance(list1, list):
raise Exception("list1 must be a list") # exception thrown in case list1 is not a list
if not isinstance(new_file, str):
raise Exception("new_file must be a str") # exception thrown in case new file is not a str.
# However in your code it is not clear what is the purpose of argument new_file
result = "Age\tName\tYOB\n" # \t for tab. tab is better than space is it somewhat maintains indentation of the columns
for list2 in list1:
result += "\t".join([str(x) for x in list2]) + "\n"
# list comprehension used to convert all item in tuple list2 to strings
with open("Age_file.txt", "w") as output:
output.write(result.strip())
my_func(list1, "test")
这一定是一个元组列表,我想在不使用pandaThats之类的模块的情况下完成它!我明白你说的话了。这真是信息量大,对理解过程有很大帮助,谢谢!