如何在python中对列表中的项进行计算?

2024-05-18 23:32:35 发布

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

我有这个测试文件:

123 52 65 75 
40 58 34 8

98 89 89 98 
45 34 29 49

我想把每两个数字相乘。我有些问题。我知道我应该做一些作业,从x=0开始,到x+=1结束,有一个计数器等等,但是我需要帮助来开始。你知道吗

以下是我目前掌握的情况:

我有一个满是数字的文件,我想把文件中的每三个数字相加,然后除以2。以下是我目前掌握的情况:

text= input('file: ')
f = open(text, 'r')
for line in f:
    counter = 0
    for n in line:
        counter *= int(n)
    print(counter)

这会将行中的所有数字相乘,但我只需要每两个。我觉得我很接近,但需要一些建议。你知道吗


Tags: 文件textinforinput作业linecounter
3条回答

正如彼特所说,你可以在一个列表中完成。你知道吗

对于初学者,我认为for循环更容易阅读。在对象上调用enumerate()会得到一个迭代器。你知道吗

line = [4, 5, 7, 8]
product = 1
# loop_number counts up from 1
for loop_number, value in enumerate(line, start=1):
    print('LOOP_NUMBER_(ITERATOR)_IS: ' + str(loop_number))
    product *= value
    print('PRODUCT IS NOW: ' + str(product))
    if loop_number % 2 == 0:
        print('OUTPUT PRODUCT: ' + str(product))
        product = 1

输出:

LOOP_NUMBER_(ITERATOR)_IS: 1
PRODUCT IS NOW: 4
LOOP_NUMBER_(ITERATOR)_IS: 2
PRODUCT IS NOW: 20
OUTPUT PRODUCT: 20
LOOP_NUMBER_(ITERATOR)_IS: 3
PRODUCT IS NOW: 7
LOOP_NUMBER_(ITERATOR)_IS: 4
PRODUCT IS NOW: 56
OUTPUT PRODUCT: 56

使用内联的。 像这样的?你知道吗

[line[n] * line[n+1] for range(0,len(line),2)]

I would like to take every two numbers and multiply them together.

最好发布:

  1. 你的起始数据。你知道吗
  2. 你想要的实际结果

如果要将成对的数字相乘,如下所示:

[1, 2, 3, 4]

1 * 2 => 2
3 * 4 => 12

然后你可以这样做:

import csv
import itertools as it

with open('data.txt', newline='') as f:
    csv_reader = csv.reader(f, delimiter=' ')

    for row in csv_reader:
        print(row)   #=> ['1', '2', '3', '4']

        every_other0 = it.islice(row, 0, False, 2)  #Produces items from the row at index 0, 2, etc.
        every_other1 = it.islice(row, 1, False, 2)  #Produces items from the row at index 1, 3, etc.

        while True:
            str1 = next(every_other0, None)  #if there are no more items in every_other0, return False
            str2 = next(every_other1, None)  #if there are no more items in every_other1, return False

            if str1 and str2:  #if either str1 or str2 is False, the condition is False
                num1 = int(str1)
                num2 = int(str2)
                print("{} * {} = {}".format(num1, num2, num1*num2))
            else:
                break

$ cat data.txt
1 2 3 4
5 6 7 8

~/python_programs$ python3.4 prog.py
['1', '2', '3', '4']
1 * 2 = 2
3 * 4 = 12
['5', '6', '7', '8']
5 * 6 = 30
7 * 8 = 56

根据您的代码:

counter = 0
for n in line:
    counter *= int(n)

也许你想要的是如下的东西:

import operator as op
import functools as funcs
import csv

with open('data.txt', newline='') as f:  #opens the file and automatically closes the file when the block is exited for any reason including if an exception occurs
    csv_reader = csv.reader(f, delimiter=' ')

    for row in csv_reader:
        every_other = [int(item) for item in row[::2] ] #=> row[::2] is equivalent to row[0:len(row):2], which means get the element at index 0, then add the step, 2, to the index value, and get the next element, etc., and stop at the index len(row).
        print(every_other)

[1, 1, 1]

        result = funcs.reduce(op.mul, every_other)  #multiply all the numbers in every_other together, reducing them to one number
        print(result)

1

        every_other = [int(item) for item in row[1::2] ] #=> row[1::2] is equivalent to row[1:len(row):2], which means start at index 1 and stop at a the end of row, and get the element at index 1; add the step, 2, to the index value, and get the element at that index, etc. 
        print(every_other)

[2, 2, 2]

        result = funcs.reduce(op.mul, every_other)
        print(result)

8

相关问题 更多 >

    热门问题