我如何对python中列表中的项进行数学运算?

时间:2015-11-16 05:59:08

标签: 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)

这会将行中的所有数字相乘,但我只想要每两个。我觉得我很亲密但需要一些建议。

3 个答案:

答案 0 :(得分:1)

正如彼得所说,你可以在列表理解中做到这一点。

对于初学者,我认为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

答案 1 :(得分:0)

  

我想把每两个数字加在一起。

总是最好发布:

  1. 您的起始数据。
  2. 您想要的实际结果
  3. 如果你想将数字对相乘,就像这样:

    [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
    

答案 2 :(得分:-1)

使用内联。 像这样的东西?

.col-xs-12