【问题标题】:Check all values in a list based on index根据索引检查列表中的所有值
【发布时间】:2020-01-13 07:01:10
【问题描述】:

我有以下功能...
有没有办法我可以以某种方式添加一个循环,以便检查列表中的每个值。该代码显示了一次使用一个 elif 检查每个索引。我只是想知道是否可以在一个 elif 块中做到这一点?我的列表中有大约 500 个值,所以不能真正为每个索引创建一个 elif
我尝试过但没有奏效的方法:

for loop in range(0,5) 然后只输入elif (str(df.iloc[i]['Name']) in x):

range(0,5) 在索引参数本身中 elif (str(df.iloc[range(0,5)]['Name']) in x):

def colourcode(x):
    if ( str('default') in x): 
        return '#fff034'
    elif (str(df.iloc[0]['Name']) in x):
        return '#ff0000'
    elif (str(df.iloc[1]['Name']) in x):
        return '#ff0000'
    elif (str(df.iloc[2]['Name']) in x):
        return '#ff0000'
    else:
        return '#000000'

【问题讨论】:

    标签: python function loops if-statement


    【解决方案1】:

    是的,你可以,这里的问题是你需要一个带有映射的字典,代码如下

    code_mappings = {0: '#ff0000', 1: '#ff0000', 2: '#ff0000'}
    def color_code(x):
     if(str('default') in x):
      return '#fff034'
     for i in range(2):
      if str(df.iloc[i]['Name'] in x)
         return code_mappings[i]
     return '#000000'
    

    【讨论】:

    • @user3925163 是的,上面的代码返回单一颜色
    • 0,1,2 只是一个例子,我有一个很大的列表,不能为每个索引制作字典,还有其他方法吗?
    【解决方案2】:

    内置函数any 非常适合这个。

    如果你想测试 iloc 中的每个元素:

    def color_code(x):
        if(str('default') in x):
            return '#fff034'
        elif any(str(iloc['Name']) in x for iloc in df.iloc):
            return "#ff0000"
        return '#000000'
    

    在 iloc 的一个 ilements 切片中:

    any(str(iloc['Name']) in x for iloc in df.iloc[:3])
    

    如果 iloc 不可迭代:

    any(str(df.iloc[i]['Name']) in x for i in range(3))
    

    【讨论】:

    • 我收到以下错误 NotImplementedError: ix is not iterable
    • 我编辑处理 df.iloc 不可迭代的情况
    猜你喜欢
    • 2020-03-05
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2022-10-07
    • 2021-12-31
    相关资源
    最近更新 更多