输入验证并将元组列表转换为 txt 文件
Input validation and converting list of tuples to txt file
我正在尝试将元组列表转换为 txt 文件并对两个输入进行输入验证。顺便说一句,我试图在没有 CSV 模块的情况下做到这一点。
我得到了这个元组列表:
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
是一个 tuple
,如您的回溯中所述。您实际上是在尝试执行以下错误:
list1[(16, 'Peter' , 2005)]
听起来您想确保 每个元组 的第二项是 str
,在这种情况下,您的代码应该如下所示。我还对其进行了修改,以便您只打开文件 一次,而不是每次迭代都打开文件并继续使用您似乎根本没有使用的 new_file
参数。
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")
我正在尝试将元组列表转换为 txt 文件并对两个输入进行输入验证。顺便说一句,我试图在没有 CSV 模块的情况下做到这一点。 我得到了这个元组列表:
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
是一个 tuple
,如您的回溯中所述。您实际上是在尝试执行以下错误:
list1[(16, 'Peter' , 2005)]
听起来您想确保 每个元组 的第二项是 str
,在这种情况下,您的代码应该如下所示。我还对其进行了修改,以便您只打开文件 一次,而不是每次迭代都打开文件并继续使用您似乎根本没有使用的 new_file
参数。
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")