[英]Python Data frame: Create New Column that Conditionally Concatenates String Values from 1 or 3 Other Columns
[英]non type error when trying to write a function that calls other functions and concatenates with string values and writes the results to a file python
我正在尝试编写一个程序,该程序从一个文件中获取数据并创建另一个文件并将数据写入新文件。 第一个文件中的数据是这样的字符串“Min: [1,2,3,5,6] on line Max: [same list as the first line] and Avg: [same list as the first] 我的任务找到这个列表的最小值、最大值和平均值,然后将其写入格式为“The min of [1,2,3,5,6] is 1”等的新文件。第一行有随机字符在它之前所以我不得不使用 strip 方法摆脱那些因此我的第一个 function 看起来像它的方式。程序运行良好,直到它在最后一个 function 中断,这给我一个错误“无法将非类型与字符串连接并且那个错误来自代码中定义的最后一个 function。 请阐明错误消息。
def create_dictionary(file):
with open("input.txt", "r", encoding = "utf-8") as file:
for line in file:
line_list = line.lstrip("\ufeff")
line_list = line_list.rstrip("\n")
return line_list.lstrip("avg :")
def integer_list(numbers):
num_list = numbers.split(",")
cast_int = [int(i) for i in num_list]
return (cast_int)
def min_value(new_list):
print(min(new_list))
def max_value(new_list):
print(max(new_list))
def average(avg):
avg = sum(new_list)/len(new_list)
print(avg)
def write_to_file(minimum, maximum, mean):
with open("output.txt", "w") as file_output:
output = file_output.write("The min of" + string_list + "is" + minimum + "\n" +
"The max of" + string_list + "is" + maximum + "\n" + "The avg of" + string_list + "is" + mean)
return output
file = ''
num_list = []
cast_int = []
avg = 0
file_output = ''
string_list = "[1,2,3,5,6]"
numbers = create_dictionary(file)
new_list = integer_list(numbers)
minimum = min_value(new_list)
maximum = max_value(new_list)
mean = average(avg)
write_to_file(minimum, maximum, mean)
您的函数 min_value/max_value 仅使用“打印”function,它不返回任何内容。 因此,最小值/最大值未定义且没有类型。 尝试这个:
def max_value(new_list):
return max(new_list)) # this is the important line as it returns the value
一旦你对 min_value function 也这样做了,你将获得正确的最大值/最小值作为数字。 要将它们转换为字符串,请使用 str() function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.