【问题标题】:Multiplying corresponding elements from 2 lists in Python在Python中将2个列表中的相应元素相乘
【发布时间】:2020-07-05 23:20:53
【问题描述】:

我是 Python 新手,想知道是否有人可以帮助解释如何使用标准输入在 Python 中编写以下任务


编程挑战说明: 您有 2 个正整数列表。编写一个程序,将这些列表中的相应元素相乘。

输入: 您的程序应该从标准输入中读取行。每行包含两个以空格分隔的列表。列表用竖线字符 (|) 分隔。两个列表的长度相同,在 [1, 10] 范围内。列表中的每个元素都是 [0, 99] 范围内的数字。

输出: 打印相乘列表。

测试输入: 9 0 6 | 15 14 9

预期输出: 135 0 54

【问题讨论】:

标签: python


【解决方案1】:

试试这个:

input_string = input().strip()
list1 = map(int, input_string.split("|")[0].split())
list2 = map(int, input_string.split("|")[1].split())
result = " ".join([str(n1*n2) for n1, n2 in zip(list1, list2)])

或,

input_string = input().strip()
list1 = input_string.split("|")[0].split()
list2 = input_string.split("|")[1].split()
result = " ".join([str(int(n1)*int(n2)) for n1, n2 in zip(list1, list2)])

或,

import operator

input_string = input().strip()
list1 = map(int, input_string.split("|")[0].split())
list2 = map(int, input_string.split("|")[1].split())
result = " ".join(map(str, map(operator.mul, list1, list2)))

print(result) 的输出:

135 0 54

【讨论】:

  • 您也可以将zip替换为map" ".join(map(str, map(operator.mul, list1, list2)))
  • @chepner 是的,这也行。我会添加这个来回答。
  • 为什么不只做str_1, str_2 = input_string.split("|"),然后map() 那些?
【解决方案2】:

由于您寻求帮助而不仅仅是解决方案,这里有一些有用的功能应该会给您一些启发:)

input("give me some") #reads a string from stdin.
"abcabcbbbc".split("c") #splits the string on "c" and returns a list. 
int("123") #converts the string to an int object.

【讨论】:

    【解决方案3】:
    #Input comma seperated values
    a = input("Values of first list: ")
    a = a.split(",")
    b = input("Valies of second list: ")
    b = b.split(",")
    c = []
    counter = 0
    for each in a:
        c.append(int(each) * int(b[counter]))
        counter += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多