简体   繁体   English

两个列表的按元素乘法

[英]Element-wise multiplication of two lists

I'm trying to write a program that takes in two lists and returns a single list that is an element-by-element multiplication of the two arguments in each of the lists. 我正在尝试编写一个包含两个列表并返回一个列表的程序,该列表是每个列表中两个参数的逐个元素相乘。
If the lists are different lengths,it should return a list that is as long as the shorter of the two. 如果列表长度不同,则返回的列表长度应与两者中的较短者相同。 Here's what I've written: 这是我写的:

s = raw_input("Enter the first list:")
c = list(s)
c = s.split()
c = map(int, c)

t = raw_input("Enter the second list:")
d = list(t)
d = s.split()
d = map(int, d)

def multiply(c, d):
    cd = [ ]
    for i in range(0, len(c)):
    cd.append(c[i]*d[i])

The general idea is that the user inputs numbers, which is converted into an integer list. 通常的想法是,用户输入数字,然后将其转换为整数列表。 However, there are errors with not being able to multiple strings with integers and "invalid literal for int() with base 10." 但是,存在无法将多个字符串与整数和“以10为底的int()无效文字”的错误。 I've been working on this for 2 hours now and I can't figure out what to do!!! 我已经为此工作了两个小时,我不知道该怎么办!!! Please help! 请帮忙!

You can try mapping with multiplication operator! 您可以尝试使用乘法运算符进行映射!

>>> from operator import mul
>>> map(mul,c,d)

Example! 例!

>>> from operator import mul
>>> c
[1, 2, 3]
>>> d
[1, 2, 3]
>>> map(mul,c,d)
[1, 4, 9]

Hope this helps! 希望这可以帮助!

You could use list comprehension mixed with zip as mentioned in this post. 您可以使用本文中提到的列表理解和zip混合。 Refer this link link . 请参考此链接

I think there're some spelling mistakes with your code.It should like this: 我认为您的代码中存在一些拼写错误,它应该像这样:

s = raw_input("Enter the first list:")
c = s.split()
c = map(int, c)

t = raw_input("Enter the second list:")
d = t.split()
d = map(int, d)

#if you want align two lists,try this:
if len(d)<len(c):
    d.extend([1]*(len(c)-len(d)))
elif len(d)>len(c):
    c.extend([1] * (len(d) - len(c)))
else:
    pass
#you will get c [2,3,1,1,1]  d[4,5,2,6,7]

cd = []
def multiply(c, d):
    for i in range(0, len(c)):
        cd.append(c[i]*d[i])

multiply(c, d)

print cd

Or you can try this: 或者,您可以尝试以下操作:

lista=raw_input("list a")

listb=raw_input("list b")


print [a*b for a,b in zip(map(int,lista.split()),map(int,listb.split()))]

Lets work on your code a bit so its easier to understand. 让我们对代码进行一些处理,使其更易于理解。 You were accidentally giving wrong inputs etc..; 您不小心输入了错误的输入等。

s = raw_input("Enter the first list:")
c = s.split()
c = list(map(int, c))

t = raw_input("Enter the second list:")
d = t.split()
d = list(map(int, d))

def multiply(c, d):
    cd = [ ]
    for i in range(0, len(c)):
        cd.append(c[i]*d[i])
    return cd

print multiply(c, d)

But of course you can do it in one line or more pythonic way using list comprehension like other answers said. 但是,当然,您可以像其他答案所说的那样,使用列表理解功能以一行或多种pythonic方式进行操作。

Let's take this a step at a time. 让我们一次迈出这一步。

First, we know that we need to read in two list of numbers from the user. 首先,我们知道我们需要从用户那里读入两个数字列表。 For the sake of simplicity, let us assume that the user can entire a list of numbers by entering one or more space-sperated values. 为了简单起见,让我们假设用户可以通过输入一个或多个以空格分隔的值来完整列出数字。 eg. 例如。

1 2 3 4 5

Now that we have defined how our input is going to be entered, we can properly parse it. 既然我们已经定义了输入的方式,我们就可以正确地解析它了。 To do so, we will first split the input into a list of strings using .split() , and then convert each string to an actual number using a list comprehension. 为此,我们将首先使用.split()将输入拆分为字符串列表,然后使用列表.split()将每个字符串转换为实际数字。 But since we'll have to use this logic two times, lets encapsulate it in a function called get_numbers() : 但是由于必须两次使用此逻辑,因此将其封装在一个名为get_numbers()的函数中:

def get_numbers():
    numbers = input("Enter some numbers: ").split()
    return [int(n) for n in numbers]

Now we can use our new function to gather two lists of numbers from the user. 现在,我们可以使用新功能从用户那里收集两个数字列表。 I'll name the first list list1 and the second list2 : 我将命名第一个列表list1和第二个list2

list1 = get_numbers()
list2 = get_numbers()

Now that we've solved the problem of getting the user input into lists, we can turn our attention to the second part of the problem: 现在,我们已经解决了将用户输入放入列表的问题,我们可以将注意力转向问题的第二部分:

return[ing] a single list that is an element-by-element multiplication of the two arguments in each of the lists. 返回单个列表,该列表是每个列表中两个参数的逐元素相乘。 If the lists are different lengths, it should return a list that is as long as the shorter of the two. 如果列表长度不同,则应返回一个长度与两者中较短者相同的列表。

Let's start off by just fulfilling the first requirement, then we'll later handle the second. 让我们首先满足第一个需求,然后再处理第二个需求。

We know that we need to grab each element n-th element from the two list in pairs, multiple them together, and put the result in a new a list. 我们知道我们需要成对地从两个列表中抓取每个元素的第n个元素,将它们多个在一起,然后将结果放入一个新的列表中。 To accomplish the task of iterating over the list in pairs, we can use zip() . 为了完成成对遍历列表的任务,我们可以使用zip() Again, we'll use a list comprehension instead of a regular for loop: 同样,我们将使用列表推导而不是常规的for循环:

[a*b for a, b in zip(list1, list2)] [a * b中的a,b用zip(list1,list2)表示]

Now let's also wrap the in a function for connivence, and call it zip_and_multiply() : 现在,我们也将其包装在一个函数中以zip_and_multiply()功能,并将其zip_and_multiply()

def zip_and_multiply(list1, list2):
    return [a*b for a, b in zip(list1, list2)]

However, without realizing it, we've also fulfilled our second requirement( "If the lists are different lengths, it should return a list that is as long as the shorter of the two." ). 但是,在没有意识到的情况下,我们还满足了我们的第二个要求( “如果列表的长度不同,则它应返回的长度等于两个中较短的一个。” )。

You see, if zip() is given two lists of different lengths, it stops zipping at the end of the shortest of the two lists, thus, it perfectly fulfills the second requirement. 您会看到,如果给zip()两个不同长度的列表,它将在两个列表中最短的列表的末尾停止压缩,因此,它完全可以满足第二个要求。

All that's left to do is to print the result of zip_and_multiply() used on list1 and list2 (the variables): 剩下要做的就是打印在list1list2 (变量)上使用的zip_and_multiply()的结果:

print zip_and_multiply(list1, list2)

After writing all of the above code(phew!), our final program in totality would be(Note this is in a different order than how the code appeared above): 编写完所有上述代码(phew!)后,最终我们的最终程序将是(请注意,其顺序与上面代码的显示顺序不同):

def get_numbers():
    numbers = input("Enter some numbers: ").split()
    return [int(n) for n in numbers]

def zip_and_multiply(list1, list2):
        return [a*b for a, b in zip(list1, list2)]

list1 = get_numbers()
list2 = get_numbers()

print zip_and_multiply(list1, list2)

One should note however, the above code is missing many sections of code which are normally in said programs, such as proper error handling. 然而,应该注意的是,上述代码缺少所述程序中通常存在的许多代码部分,例如适当的错误处理。

Firstly, List Comprehension is all you need for your problem. 首先, 列表理解是解决问题所需要的。 Now lets breakdown your problem - 现在让我们解决您的问题-

Get input from user - for the 从用户那里获取输入 -

"errors with not being able to multiple strings with integers" “无法使用整数对多个字符串进行错误处理”

problem, assuming that you are working on integer values, you need to make sure that all the values in the lists are of type int . 问题,假设您正在处理整数值,则需要确保列表中的所有值均为int类型。 You can make the user enter the values and map it to int type making use - 您可以使用户输入值并将其映射到int类型,以使用-

user_input = map(int, raw_input("Enter the first list:").strip().split(' ')) user_input = map(int,raw_input(“输入第一个列表:”)。strip()。split(''))

This will take space separated integers from users and convert them to a list. 这将从用户处使用空格分隔的整数并将其转换为列表。

Now for 现在

"invalid literal for int() with base 10." “以10为基数的int()的无效文字”

you need to make sure that only integers are being entered while taking the input from the user. 您需要确保在从用户处获取输入时仅输入整数。 In case user provide a string or an empty response it will throw this error. 如果用户提供字符串或空响应,则将抛出此错误。

Multiply two Lists - While multiplying yours list following scenarios can arise : 将两个列表相乘-将列表相乘会出现以下情况:

1.Both lists are of same length. 1.两个列表的长度相同。

2.Both lists are of unequal length. 2.两个列表的长度不相等。

You need to check the length of lists and if length differ then multiply the elements form both lists until the elements from smaller list are exhausted and append the remaining elements from larger list. 您需要检查列表的长度,如果长度不同,则将两个列表中的元素相乘,直到用完较小列表中的元素,然后追加较大列表中的其余元素。 Below is the code snippet for your problem statement - 以下是您的问题陈述的代码段-

c = map(int, raw_input('Enter First List').strip().split(' '))
d = map(int, raw_input('Enter Second List').strip().split(' '))

answer = [c[i]*d[i] if i<min(len(c), len(d)) else (c[i] if \
len(c)>len(d) else d[i]) for i in xrange(max(len(c), len(d)))]

answer will contain the desired result set. 答案将包含所需的结果集。

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

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