需要以空格和反i分隔的行作为输入

2024-04-26 07:26:32 发布

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

需要在一行中获取输入并用空格分隔,反转它并添加输出

我尝试了raw\u input().split()

for i in raw_input("Enter the numbers: ").split():
   print(i)

如果数组A有元素[1,2,3],那么数组A的反方向将是[3,2,1],结果数组应该是[4,4,4]。你知道吗

Input:
4
2 5 3 1

Output:
3 8 8 3

Tags: thein元素forinputoutputraw数组
3条回答

要从用空格分隔的数字字符串中获取列表,可以使用^{}。要遍历列表,可以使用^{}^{}用于从头到尾遍历列表,^{}-将原始列表中的元素连接起来并将结果传递给^{}^{}用提供的分隔符连接列表的元素。你知道吗

代码(python 2)

limit = raw_input("Enter amount of numbers: ")
if limit.decode("utf-8").isdecimal():       # check if string contains only digits
    inp = raw_input("Enter the numbers: ")
    if int(limit) <= inp.count(" ") + 1:    # amount of spaces + 1 is amount of numbers
        a = map(int, inp.split(" "))        # split string and convert str to int
        b = map(sum, zip(a, reversed(a)))   # sum elements of input list and reversed
        res = " ".join(map(str, b))         # convert result to str and join to string

代码(python 3)

limit = input("Enter amount of numbers: ")
if limit.isdecimal():
    inp = input("Enter the numbers: ")
    if int(limit) <= inp.count(" ") + 1:
        a = list(map(int, inp.split(" ")))
        b = list(map(sum, zip(a, reversed(a))))
        res = " ".join(map(str, b))

我想有很多方法可以解决这个问题。 也许你可以试试这个。你知道吗

n = int(input())
arr = list(map(int, input().split()))
assert n == len(arr)
result = list(map(lambda elem: elem[0] + elem[1], zip(arr, reversed(arr))))
print(result)

或者只是

n = int(input())
arr = list(map(int, input().split()))
assert n == len(arr)
for i, elem in enumerate(arr):
    print(elem + arr[n-i-1], end=' ')

随便问吧。你知道吗

您可以这样做:

a=[2,5,3,1]
b = [x + y for x, y in zip(a, a[::-1])]
print(b) # -> [3, 8, 8, 3]

相关问题 更多 >