简体   繁体   English

在列表python中相乘

[英]multiplying in a list python

I am doing some homework and I am stuck. 我正在做一些功课,我被困住了。 I supposed to write a code in Python 3, that reads a text file that is like a bill with an amount of numbers. 我应该在Python 3中编写一个代码,它读取的文本文件就像是一个带有大量数字的账单。 I am supposed to write the code so it will calculate the total amount. 我应该编写代码,以便计算总金额。

I figured that a bill(simple example) will contain a number and the a prise. 我认为一个账单(简单示例)将包含一个数字和一个奖品。 like: 喜欢:

2 10$
1 10 $
and so on

So I figured that I create a list with all numbers in it and then I want to multiply the first with the second element in the list and then jump in the list so the tird and the fourth element get multiply and so on, until there is no more numbers in my list. 所以我想我创建了一个包含所有数字的列表然后我想将第一个与列表中的第二个元素相乘,然后在列表中跳转,这样第三个和第四个元素相乘,依此类推,直到有我的列表中没有更多数字。 During this happens I want the sums of every multiplication in a new list called sums there they later will be summed. 在这种情况下,我想要一个名为sums的新列表中的每个乘法的和,它们稍后将被求和。

my code looks like this so far: 我的代码到目前为止看起来像这样:

file = open('bill.txt')
s = file.read()
file.close()



numbers = []
garbage = []

for x in s.split():
    try:
        numbers.append(float(x))
    except ValueEror:
        garbage.append()
print(numbers)


for n in numbers:
    sums = []
    start = 0
    nxt = start + 1
    t = numbers[start]*numbers[nxt]    
    if n <= len(numbers):
        start += 2
        nxt += 2
        summor.append(t)
    if n == len(numbers):
        print(sum(sums))

The problem in your code is likely that you keep resetting sums for every number in the list. 您的代码中的问题可能是您不断重置列表中每个数字的sums So you basically keep forgetting the sums you previously collected. 所以你基本上忘记了之前收集的金额。 The same applies to start and nxt . 这同样适用于startnxt If you move these definition outside of the loop, and also fix the summor.append(t) to sums.append(t) it should almost work. 如果将这些定义移到循环之外,并将summor.append(t)修复为sums.append(t)它应该几乎可以工作。 Also note that the loop variable n does not iterate over indexes of numbers but over the actual items (ie the numbers). 还要注意的是循环变量n 超过指标迭代numbers ,但在实际的项目(即数字)。 So the check at the end n == len(numbers) is unlikely to do what you expect. 所以最后的检查n == len(numbers)不太可能达到你的预期。 Instead, you can just put the print after the loop because you know that when you reached that point the loop is over and all numbers have been looked at. 相反,您可以在循环之后放置打印因为您知道当您到达该点时循环结束并且所有数字都已被查看。


A common idiom is to use zip to combine two elements with each other. 一个常见的习语是使用zip将两个元素相互组合。 Usually, you use zip on two different iterators or sequences, but you can also use zip on the same iterator for a single list: 通常,您在两个不同的迭代器或序列上使用zip,但您也可以在同一个迭代器上使用zip作为单个列表:

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> it = iter(numbers)
>>> for a, b in zip(it, it):
        print(a, b)

1 2
3 4
5 6
7 8

As you can see, this will group the numbers automatically while iterating through the list. 如您所见,这将在迭代列表时自动对数字进行分组。 So now you just need to collect those sums: 所以现在你只需要收集这些款项:

>>> sums = []
>>> it = iter(numbers)
>>> for a, b in zip(it, it):
        sums.append(a * b)

>>> sum(sums)
100

And finally, you can shorten that a bit more using generator expressions: 最后,您可以使用生成器表达式缩短一点:

>>> it = iter(numbers)
>>> sum(a * b for a, b in zip(it, it))
100

This may be a typo when you entered it but on your 2nd line of data there is a space between the amount and $ and no space on the line above. 这可能是您输入时的拼写错误,但在您的第二行数据上,金额和$之间有一个空格,上面一行没有空格。 This will cause some problems when striping out the $. 在删除$时会出现一些问题。

Try this: 尝试这个:

total = 0
with open('data.txt', 'r') as f:
    lines = f.readlines()
    amounts = []
    garbage = []
    for line in lines:
        try:
            multiples = line.split()
            multiplier = multiples[0]
            amount = multiples[1].strip('$\n')
            amounts.append(int(multiplier)*float(amount))
        except:
            garbage.append(line)
    total = sum(amounts)
print(total)

With some minor formatting on output or the text data you should be able to get the result you want. 通过输出或文本数据上的一些小格式,您应该能够获得所需的结果。 Here is the txt data I used: 这是我使用的txt数据:

2 10$
1 10$
3 20.00$

and the output is: 输出是:

90.0

Also, you may want to get away from file = open('data.txt', 'r') which requires you to explicitly close your file. 此外,您可能希望摆脱file = open('data.txt','r'),这需要您明确关闭文件。 Use with open('data.txt', 'r') as f: and your file will implicitly be closed. 使用open('data.txt','r')作为f:并隐式关闭您的文件。

Firstly, I would say, quite a good attempt. 首先,我想说,这是一次非常好的尝试。 If you don't want to be spoiled, you should not read the code I have written unless you try out the corrections/improvements yourself. 如果您不想被宠坏,除非您自己尝试更正/改进,否则不应阅读我编写的代码。 (I am not a pro) (我不是专业人士)

Well, like you said every line contains 2 numbers that need be multiplied, you should start by reading line by line & not individual numbers as that might get troublesome. 好吧,就像你说每行包含2个需要乘法的数字一样,你应该先逐行阅读而不是个别数字,因为这可能会让人感到麻烦。

file = open('bill.txt')
s = file.readlines()
file.close()

numbers = []
garbage = []

for line in s:
    try:
        line.strip('$') # removes the trailing $ sign for easy number extraction
        numbers.append(map(int, line.split()))
    except ValueEror:
        garbage.append(line)
print(numbers)

Later, when summing up the multiplication of the number & the bills, you probably won't require a list for that, instead a sum integer variable should be enough. 后来,当总结数字和账单的乘法时,你可能不会需要一个list ,而是一个求和整数变量就足够了。

sum = 0
for num, bill in numbers:
    sum += num * bill
print("The total amount is", sum)

Several things: 几件事:

  • sums = [] is inside the loop for n in numbers . sums = [] for n in numbers循环内。 This means you're resetting the sums list every time. 这意味着您每次都要重置sums列表。 You should move this outside the loop. 你应该把它移到循环之外。
  • The same applies to start = 0 and nxt = start + 1 . 这同样适用于start = 0nxt = start + 1 These values now keep being reset to 0 and 1 respectively for each number in the list. 现在,对于列表中的每个数字,这些值将分别重置为01
  • You are comparing if n <= len(numbers): but what is n ? 你正在比较if n <= len(numbers):但是n什么? It's an actual value in your list of numbers, it doesn't represent the position in the list. 它是您的数字列表中的实际值,它不代表列表中的位置。 You should replace this with while start < len(numbers): - as long as the starting position is still within the list we should keep going. 你应该用while start < len(numbers):替换它while start < len(numbers): - 只要起始位置仍然在列表中我们应该继续。 This also means you can remove n from your code. 这也意味着您可以从代码中删除n

The code now becomes: 代码现在变成:

sums = []
start = 0
nxt = start + 1
while start < len(numbers):
    t = numbers[start]*numbers[nxt]    
    start += 2
    nxt += 2
    sums.append(t)

print(sum(sums))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM