Python - 在LIST中反转字符串的函数 [英] Python - Function to reverse strings in LIST

查看:118
本文介绍了Python - 在LIST中反转字符串的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这一次关于函数,我需要创建2个函数,首先用于数字来总结用户输入的所有内容在列表和第二个函数中,用户输入一些单词到列表和函数中,而不用触及列表中的单词索引,获取每个单词并返回相反的单词(在同一个索引上)

我可以告诉你我的代码,我认为我没有数字和它的功能问题,我需要你的帮助反向功能,我尝试了一些方法,甚至一个for在另一个,但我更喜欢一些简单的方法。

  def sum(数字):
acc = 0
数字麻木:
acc + =麻木
返回acc

def rever(字符串):
r = []
为字符串中的i:
为n i:
reverse(r [n])
return r

numbers = [int(x)for x in input(请输入至少5个数字(使用空格) :).split()]
pri nt(sum(numbers))
strings = [str(x)for x in input(请输入至少5个单词(Use Space):).split()]
print(rever(字符串))


解决方案

作为同名内置函数( sum())。第二,你可以使用一个简单的列表理解。

  def rever(字符串):
return [x [ :: - 1] for x in strings]


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))

解决方案

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]

这篇关于Python - 在LIST中反转字符串的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆