如何迭代地将一些值分配给不同的变量

时间:2015-10-08 22:35:21

标签: python postgresql

假设我有一个列表

 [('maindb', 'localhost', 'postgres', 'root')]

我希望迭代地将这些值分配给4个不同的变量,这将是什么方式?

我试过了

[db, host, user, password] = [x for x in user_list]

但这不起作用。错误:

ValueError: need more than 1 value to unpack

2 个答案:

答案 0 :(得分:2)

  

你应该使用它。

db, host, user, password = user_list[0]

答案 1 :(得分:2)

不清楚你要做什么:

    <basename property="jar.name" file="D:\SomeDir\Tomcat7\lib\commons-httpcore-4.4.2.jar"/> <!-- this would be the file name being deployed - ideally passed in as a property to a target -->

    <propertyregex property="jar.base.name" override="true"
          input="${jar.name}"
          regexp="^(.*)-\d+\.\d+\.\d+(\.jar)$"
          replace="\1*.jar"
          casesensitive="false" 
          defaultValue="${jar.name}"/>

    <echo message="Backing up/undeploying '${jar.name}' from Tomcat..." level="info"/>
    <echo message="Base JAR name is: '${jar.base.name}'" level="info"/>
    <!-- this will result in commons-httpcore*.jar -->

    <fileset id="target.file" dir="D:\SomeDir\Tomcat7\lib" includes="**/${jar.base.name}"/>

    <condition property="target.file.found" value="true" else="false">
        <resourcecount refid="target.file" when="greater" count="0"/>
    </condition>
    <echo message="File to be backed up found? '${target.file.found}'"/>

与原始user_list相同,但假设您有4元组列表,那么您可以这样做:

[x for x in user_list]

或者更简洁:

for x in user_list:
    db, host, user, password = x
    <logic>

如果您希望对这些值进行命名访问以提高代码的可读性,那么您可以查看for db, host, user, password in user_list: <logic> 并创建一个命名元组列表。以下是namedtuple的工作方式:

namedtuple

并创建这些命名元组的列表:

from collections import namedtuple
Account = namedtuple('Account', ['db', 'host', 'user', 'password'])
account = Account(user_list[0])
print(account.db, account.host, account.user, account.password)