【问题标题】:Python3 multiple equal sign in the same linePython3多个等号在同一行
【发布时间】:2021-06-09 02:56:01
【问题描述】:

python2 代码中有一个函数,我正在将其重写到 python3 中

def abc(self, id):

    if not isinstance(id, int):

        id = int(id)

    mask = self.programs['ID'] == id
    assert sum(mask) > 0

    name = self.programs[mask]['name'].values[0]

这里的“id”是一个panda系列,索引是字符串,列是int,如下所示

data = np.array(['1', '2', '3', '4', '5'])
  
# providing an index
ser = pd.Series(data, index =['a', 'b', 'c'])
print(ser)

self.programs['ID'] 是一个数据框列,其中有一行包含像 '1' 这样的整数数据

import pandas as pd
  
# initialize list of lists
data = [[1, 'abc']]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['ID', 'name'])

我真的对“mask = self.programs['ID'] == id \ assert sum(mask) > 0”这一行感到困惑。有人能解惑吗?

【问题讨论】:

  • mask = self.programs['ID'] == id 如果添加隐式括号会更容易阅读:mask = (self.programs['ID'] == id)
  • 断言会更好assert np.any(mask)

标签: python-3.x python-2.7


【解决方案1】:

基本上,mask = self.programs['ID'] == id 将返回一系列布尔值,无论这些“ID”值是否等于 id。

然后assert sum(mask) > 0 总结布尔系列。请注意,bool True 在 python 中可以被视为 1,而 0 则为 False。所以这断言,至少有一种情况是programs['ID'] 列的值等于id。

【讨论】:

    猜你喜欢
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 2018-08-11
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多