如何解决如何使用Python将文本文件中同一行上的数字相乘?
对不起,如果这个问题很简单,我仍在学习Python。
我正在尝试制作一个程序来遍历文本文件中的每一行,将同一行的数字相乘,然后将这些数字的乘积分配给一个名为product的变量。
例如,如果文本文件的第一行读取“ 1 2 3”,则程序将获得这些数字的乘积(6)并将其分配给名为product1的变量,并且它将继续为每个变量执行此操作文件中的行,将单独的变量分配给每行的乘积。然后,我的程序将输出每一行的乘积。
到目前为止,我的程序是: ''' file = open(“ apples”,“ r”)
for line in infile:
num = str(line)
num = num.split(' ')
num = int(num)
total += num
print(num)
'''
Num只是一个占位符变量。
文本文档示例:
1 2 3
3 2 5
2 2 2
任何帮助将不胜感激。 谢谢。
解决方法
您的程序几乎是正确的,只是微小的改进:
-
最好在上下文管理器的帮助下打开文件:
with ...
-
num = str(line)
不是必需的,line
已经是字符串 -
您应该跳过空行
-
借助另一个for循环计算该行的乘积
-
将产品存储在列表中,然后打印
示例:
all_products = []
with open('<your file.txt>','r') as f_in:
for line in f_in:
numbers = [*map(int,line.split())]
# skip empty lines:
if not numbers:
continue
product = 1
for n in numbers:
product *= n
all_products.append(product)
# print all products:
for line,product in enumerate(all_products,1):
print('Line: {} Product: {}'.format(line,product))
打印:
Line: 1 Product: 6
Line: 2 Product: 30
Line: 3 Product: 8
,
from functools import reduce
file = open("apples",r)
products = {}
i = 1
for line in file:
product = reduce((lambda x,y: x * y),str(line).split(' '))
products['product{}'.format(i)] = product
i += 1
print(products)
,
def prod(line):
x=1
for n in num:
x = x * int(n)
return x
product = []
for line in infile:
num = line.split(' ')
product.append(prod(num))
print(product)
我认为这会达到您的目的
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。