【问题标题】:how to append to multiple lists inside a list如何附加到列表中的多个列表
【发布时间】:2017-10-20 14:45:19
【问题描述】:
def get_users(self, department_ids, selectable=User, is_alive=True, except_main_department_owner=False):
    """
        Returns all users of given departments
    """
    query_ob = self.session.query(selectable).join(User.departments).filter(
        Department.id.in_(department_ids))

    if except_main_department_owner:
        query_ob = query_ob.filter(
            User.id != DefaultValue.DEFAULT_MAIN_DEPARTMENT_OWNER_ID
        )

    if is_alive:
        query_ob = query_ob.filter(
            User.is_alive
        )

    return query_ob.all()

当我调用传递一个单独的 id 时,例如:

d_user = [helper.get_users([1], is_alive=True, except_main_department_owner=True)]

它返回值。

但是当我想要一系列列表时:

helper = DepartmentHelper(self.session, self.login_user)
d_user = [helper.get_users([id], is_alive=True, except_main_department_owner=True) for id in self.data_departments]

它给我一个错误。

"Failed processing pyformat-parameters; %s" % err)
sqlalchemy.exc.ProgrammingError: 
(mysql.connector.errors.ProgrammingError) Failed processing pyformat-
parameters; 'MySQLConverter' object has no attribute 
'_department_to_mysql'  

【问题讨论】:

  • 您是否尝试将列表附加到列表中?和列表一样吗?
  • 能不能也加个输入和对应输出的例子
  • each_department_lists_of_users = [[],[],[],[],[],....,[]],我想向其中添加用户,例如 each_department_lists_of_users = [[ 1,2,3,4],[6,7,8],...,[89,89]]
  • 你能不能说得更具体一点,我们无法理解你到底想要什么
  • 所以,我有 n 个部门,对于每个部门,我有 n 个用户。我创建了一个列表,其中有 n 个列表,每个列表将包含 n 个用户

标签: python mysql database list sqlalchemy


【解决方案1】:

在你的linked question(我认为你应该坚持一个问题,并努力制定一个SSCCE),你指定你从这个函数中获取你的用户:

def get_users(self, department_ids, selectable=User, is_alive=True, except_main_department_owner=False):    
    """Returns all users of given departments

    """
    query_ob = self.session.query(selectable).join(User.departments).filter(
        Department.id.in_(department_ids))

    return query_ob.all()

从您的 cmets 中,您指定您的部门编号为 1..n。然后,您可以获得具有列表理解的用户列表列表:

n = 9
department_ids = range(1,n+1)
users_per_department = [self.get_users([id]) for id in department_ids]

【讨论】:

  • 但我不希望每个列表中都有相同的重复版本。每个列表都有不同的用户
  • 您能否举一个原始users_per_department 列表的示例以及添加用户后您希望它是什么?
  • stackoverflow.com/questions/44079900/… 看看这个,如果有帮助
  • 部门 = [1,2,3,4,...,n] 用户 = [1,2] 部门 1 用户 = [3,4] 部门 2 .....部门列表 = [[],[],[],[],,...,[]] 所以我想要,部门列表 = [[1,2],[3,4] ..., [] ]
  • 你收到了吗?
【解决方案2】:

您可以通过以下示例实现此目的

department=[]
department.append([1,2,..])

所以:

department=[[1,2,],]

【讨论】:

  • 这是你想要的吗?
【解决方案3】:

您可以使用方括号(从零开始计数)引用列表项:

some_list = [[],[],[]]
some_list[1] += [1,2,3]

现在some_list 包含[[], [1, 2, 3], []]

【讨论】:

    【解决方案4】:

    我不确定您的确切要求,但我认为您是在询问连接两个列表。

    list1=list2+list3
    

    这将连接两个列表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-21
      • 2012-12-20
      • 1970-01-01
      • 2022-12-06
      • 2021-10-02
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      相关资源
      最近更新 更多