将一行中的变量设置为等于两个if语句

时间:2019-07-09 20:19:53

标签: python if-statement

我需要变量像这样工作:

fppg_multiplier = 2 if row['Roster Position']
== 'MVP' else 1.5 if row['Roster Position'] == 'STAR' else 1

我如何在一排中做到这一点?

@SitesRegistry.register_csv_importer
class DraftKingsCaptainModeCSVImporter(DraftKingsCSVImporter):  # pragma: nocover
        site = Site.DRAFTKINGS_CAPTAIN_MODE

        def _row_to_player(self, row):
            try:
                fppg_multiplier = 2 if row['Roster Position'] == 'MVP' else 1
                fppg_multiplier = 1.5 if row['Roster Position'] == 'STAR' else 1
                name = row['Name'].split()
                player = Player(
                    row['ID'],
                    name[0],
                    name[1] if len(name) > 1 else '',
                    row['Roster Position'].split('/'),
                    row['TeamAbbrev'],
                    float(row['Salary']),
                    float(row['AvgPointsPerGame']) * fppg_multiplier,
                    game_info=self._parse_game_info(row),
                    **self.get_player_extra(row)
                )
            except KeyError:
                raise LineupOptimizerIncorrectCSV
            return player

2 个答案:

答案 0 :(得分:2)

如果我将所有代码放在一行上,那么您的代码对我有用:

>>> row = {}
>>> row['Roster Position'] = 'MVP'
>>> fppg_multiplier = 2 if row['Roster Position'] == 'MVP' else 1.5 if row['Roster Position'] == 'STAR' else 1
>>> fppg_multiplier
2
>>> row['Roster Position'] = 'STAR'
>>> fppg_multiplier = 2 if row['Roster Position'] == 'MVP' else 1.5 if row['Roster Position'] == 'STAR' else 1
>>> fppg_multiplier
1.5
>>> row['Roster Position'] = 'XXX'
>>> fppg_multiplier = 2 if row['Roster Position'] == 'MVP' else 1.5 if row['Roster Position'] == 'STAR' else 1
>>> fppg_multiplier
1

答案 1 :(得分:1)

如果单行编写至关重要,则可以编写如下自定义函数:

def getval(x):
    if x=='MVP':
        return(2)
    elif x=='STAR':
        return(1.5)
    else:
        return(1)

然后只要需要就可以调用该函数。例如:

fppg_multipler = getval(row['Roster Position'])