Python枚举列表的良好编程习惯 [英] Python good programming practice for enumerating lists

查看:76
本文介绍了Python枚举列表的良好编程习惯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一般对Python和程序设计还很陌生,我想知道用许多逻辑运算符(例如,在for循环中)编写长语句是否是一种好的编程习惯.

I'm pretty new to Python and programming in general, and I was wondering if it is a good programming practice to write long statements with many logic operators - for example, in a for loop.

例如,这是我制作的一个函数,该函数从一个单词中获取所有元音,并返回包含这些元音的列表.

For example, here's a function I made that gets all the vowels from a word and returns a list containing those vowels.

def getVowels(word):
    vowel_list = []
    index = 0
    for i in word:
        if i == "a" or i == "e" or i == "i" or i == "o" or i == "u" or i == "A" or i == "E" or i == "I" or i == "O" or i == "U":
            vowel_list.append(word[index])
        index += 1
    return vowel_list

如您所见,if语句已经很长了.它被认为是好的编程吗?如果不是,是否有更好的方法编写此函数?

As you can see, the if statement has gotten very long. Is it considered good programming? If it's not, is there a better way to code this function?

推荐答案

不,这不是好方法,总有更好的方法:D

No it is not considered good practice, there are always better ways :D

if i.upper() in "AEIOU"

这是使用列表推导功能的简短版本:

Here is a much shorter version of your function using list comprehensions:

def get_vowels(word):
    vowels = "AEIOU"
    return [c for c in word if c.upper() in vowels]

这篇关于Python枚举列表的良好编程习惯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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