问题
studying Python as crazy and have many many questions.
This time about function, i need to create 2 functions, first for numbers to sum up everything that user inputs in the list and second function, where user inputs some words in to the list and function without touching word indexes in the list, takes each word and returns reversed words (On the same index)
I can show you my code, i think i don't have problems with numbers and its function, i need your help with reverse function, i tried some ways, even one "for" in another, but i prefer some easy ways.
def sum(numbers):
acc = 0
for numb in numbers:
acc += numb
return acc
def rever(strings):
r = []
for i in strings:
for n in i:
reversed(r[n])
return r
numbers = [int(x) for x in input("Please input at least 5 numbers (Use space): ").split()]
print(sum(numbers))
strings = [str(x) for x in input("Please input at least 5 words (Use Space): ").split()]
print(rever(strings))
回答1:
For your first function, that already exists as a built-in function of same name (sum()
). For the second, you can use a simple list comprehension.
def rever(strings):
return [x[::-1] for x in strings]
回答2:
Judging by your question it seems you are learning functions in python
, you can reverse the list using a function like this:
strings_ = [str(x) for x in input("Please input at least 5 words (Use Space): ").split()]
for index,item in enumerate(strings_):
def recursion_reverse(string_1):
if not string_1:
return ""
else:
front_part=recursion_reverse(string_1[1:])
back_part=string_1[0]
return front_part+back_part[0]
strings_[index]=recursion_reverse(item)
print(strings_)
output:
Please input at least 5 words (Use Space): Hello world this is me
['olleH', 'dlrow', 'siht', 'si', 'em']
来源:https://stackoverflow.com/questions/47131096/python-function-to-reverse-strings-in-list