Python 使用行列表,无论我有1行还是N行

Python 使用行列表,无论我有1行还是N行,python,list,python-3.x,pyodbc,Python,List,Python 3.x,Pyodbc,我有 有时 foo=("bob","smith","123") 和for循环: foo=(("bob","smith","123"),("sam","smith","124")) 但我希望for循环将foo视为一个行列表,即使其中只有一行而不是n多行。现在,如果我只通过了第一个foo,它将由bob,smith,123进行迭代,但是如果我通过了第二个foo,它将按行进行迭代(这就是我想要的)。对象是pyodbc.Row 另一种说法是,我希望能够使用: for rows in foo: 如果我

我有

有时

foo=("bob","smith","123")
和for循环:

foo=(("bob","smith","123"),("sam","smith","124"))
但我希望for循环将foo视为一个行列表,即使其中只有一行而不是n多行。现在,如果我只通过了第一个foo,它将由bob,smith,123进行迭代,但是如果我通过了第二个foo,它将按行进行迭代(这就是我想要的)。对象是pyodbc.Row

另一种说法是,我希望能够使用:

for rows in foo:
如果我通过了很多行,或者只有一行


我该怎么做呢?

您肯定需要额外检查,因为字符串也是可编辑的。那么,为什么不为列表使用特定的格式呢

foo[0][1]=stuff
您还可以检查类型以获取元素。或者如果你坚持:

foo=(("bob",),("smith",),("123",))

为什么您不喜欢使用:

# foo = ("bob", "smith", "123")
foo=(("bob","smith","123"),("sam","smith","124"))
for rows in foo:
    a = rows if isinstance(rows, tuple) else (rows,)
    print (a[0])
然后


在接受不同类型输入的函数中,我经常使用的一个技巧是首先将不常见的输入规范化为公共类型,然后处理公共类型。同样,在您的情况下,您可以执行以下操作(未经测试):


for
中使用
if
表达式

if not isinstance(foo[0], tuple):  # only a single row
    foo = (foo,)  # add row to tuple of lenght 1 
for row in foo:  # now we are sure foo is a tuple of rows
    # do something with row

需要使行始终添加到列表中,所以foo始终是列表的列表,即使只有一行。就我个人而言,我会责怪任何函数返回
tuple
tuple
字符串,而其他时候返回
tuple
的字符串。你的意思是
foo=((“bob”,“smith”,“123”),)
而不是
foo=((“bob”、(“smith”、(“123”、))
?哦,也许我没有你真正需要的东西;)如果类型(行)不是列表,则使用:
for row in foo:
    DoSomething(row[0])
if not isinstance(foo[0], tuple):  # only a single row
    foo = (foo,)  # add row to tuple of lenght 1 
for row in foo:  # now we are sure foo is a tuple of rows
    # do something with row
for rows in (foo,) if type(foo[0]) is not tuple else foo:
    print(rows)