简体   繁体   English

Python:检查列表中是否有子字符串的优雅解决方案?

[英]Python: Elegant solution to check if any substring is in list?

Before you close this, please try to understand the question - it's a bit different, but looks like a lot of downvoted questions. 在关闭此步骤之前,请尝试理解问题-有点不同,但是看起来很多问题被否决了。

I'm looking for a simple way to check if any substrings of a string is in a list of strings. 我正在寻找一种简单的方法来检查字符串的任何子字符串是否在字符串列表中。 The input is like 2018_JAN_BGD , and I want to convert the month info in this to a (year-)quarter info. 输入类似于2018_JAN_BGD ,我想将此中的月份信息转换为( 2018_JAN_BGD )季度信息。 For example Q1 would be January, February and March. 例如,第一季度将是一月,二月和三月。 So I'm looking for a way to check if any of the substrings in 2018_JAN_BGD contains JAN , FEB or MAR . 所以我正在寻找一种方法来检查2018_JAN_BGD中的2018_JAN_BGD字符串2018_JAN_BGD包含JANFEBMAR I could do this by writing 12 (for the whole year) if-else clauses with or's, but I feel like there's a more elegant solution in Python. 我可以通过用or编写12个(全年)if-else子句来做到这一点,但是我觉得Python中有一个更优雅的解决方案。 I'm trying: 我正在努力:

def tellQuarter(month):
    Q1 = ('JAN','FEB','MAR')
    Q2 = ('APR','MAY','JUN')
    Q3 = ('JUL','AUG','SEP')
    Q4 = ('OCT','NOV','DEC')
    if any(for mon in Q1 in month):
        return ("Q1")
    if any(for mon in Q2 in month):
        return ("Q2")

This is of course incorrect (invalid syntax), but I can't figure out how to put this correctly. 这当然是不正确的(语法无效),但是我不知道如何正确地放置它。 Basically, I want to loop through Q1 , and check if any of the strings is a substring of month . 基本上,我想遍历Q1 ,并检查是否有任何字符串是month的子字符串。

I mean I can do 我是说我能做

for mon in Q1:
    if mon in month:
        return "Q1"

but isn't there a more elegant, single-line solution to this? 难道没有一个更优雅的单行解决方案吗?

Cheating, but use a dictionary, mapping the months to quarters: 作弊,但使用字典,将月份映射到季度:

monthsToQuarters = {
    'JAN': 'Q1','FEB': 'Q1','MAR': 'Q1',
    'APR': 'Q2','MAY': 'Q2','JUN': 'Q2',
    'JUL': 'Q3','AUG': 'Q3','SEP': 'Q3',
    'OCT': 'Q4','NOV': 'Q4','DEC': 'Q4'}

giving you: 给你:

>>> monthsToQuarters['JAN']
'Q1'

you could strip out the month using something like: 您可以使用类似以下方法删除月份:

>>> '2018_JAN_BGD'.split('_')[1]
'JAN'

Avoid repeating logic with a dict: 避免用dict重复逻辑:

QUARTERS = {
    'Q1': ('JAN', 'FEB', 'MAR'),
    'Q2': ('APR', 'MAY', 'JUN'),
    'Q3': ('JUL', 'AUG', 'SEP'),
    'Q4': ('OCT', 'NOV', 'DEC'),
}

def tellQuarter(month):
    for q, months in QUARTERS.items():
        if any(m for m in months if m in month):
            return q
    raise ValueError("String '{}' does not contain a month.".format(month))

print(tellQuarter('2018_JAN_BGD'))
>>> Q1

You had a syntax error in your list comprehension 您的列表理解中存在语法错误

def tellQuarter(month):
        Q1 = ('JAN','FEB','MAR')
        Q2 = ('APR','MAY','JUN')
        Q3 = ('JUL','AUG','SEP')
        Q4 = ('OCT','NOV','DEC')
        if any(mon in month for mon in Q1):
            return ("Q1")
        if any(mon in month for mon in Q2):
            return ("Q2")

print tellQuarter("2018_JAN_BGD")

Output : 输出

Q1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM