表列数&在Python中搜索值

时间:2013-09-03 15:58:30

标签: python list search count

假设我有一个名为“a”的多维表:

[['John',  8, 'Student'   ],
 ['Paul', 22, 'Car Dealer'],
 ['Nick', 30, 'Doctor'    ],
 ['Mark', 66, 'Retired'   ]]

python中是否有内置函数来计算有多少列(4)而不是这样做?:

f = 0
for item in a: f = f + 1

我也可以将上面两行合并为一个吗?


具有内置功能:

  • 如何搜索名称,在第一列中查找名称是否存在?

  • 如果存在值,如何搜索整个表?

4 个答案:

答案 0 :(得分:4)

保罗指出:

len(your_list) # Returns number of rows (which is what I assume you meant)

对于你的其他两个问题,这是你最接近内置的问题:

>>> 'Paul' in (row[0] for row in your_list)
True
>>> 66 in itertools.chain.from_iterable(your_list)
True

答案 1 :(得分:3)

您想使用内置的len

f = len(a)

答案 2 :(得分:2)

对行使用len

table=[['John',  8, 'Student'   ],
       ['Paul', 22, 'Car Dealer'],
       ['Nick', 30, 'Doctor', 'this row is longer..','making 5'],
       ['Mark', 66, 'Retired'   ]]

y=len(table)      # 4

然后你必须逐行去寻找最大宽度:

x=max(len(row) for row in table)     # 5

您可以使用列表推导来获取垂直列的值:

>>> [li[0] for li in table]
['John', 'Paul', 'Nick', 'Mark']

要查找值,您可以将生成器表达式与任何或仅测试成员资格一起使用:

any('John' in l for l in table)      # True
'Paul' in (li[0] for li in table)    # True

要查找哪一行,请使用列表解析:

[i for i,l in enumerate(table) if 'Mark' in l]   # 3

答案 3 :(得分:2)

使用数据库有效地执行所有这些操作:


创建并填充数据库:

import sqlite3
a = [['John',  8, 'Student'   ],
 ['Paul', 22, 'Car Dealer'],
 ['Nick', 30, 'Doctor'    ],
 ['Mark', 66, 'Retired'   ]]

conn = sqlite3.connect('so.db')
c = conn.cursor()
c.execute('''CREATE TABLE data
             (name text, age int, occupation text)''')
c.executemany('INSERT INTO data VALUES (?,?,?)', a)
conn.commit()
conn.close()

现在在数据库中搜索:

>>> conn = sqlite3.connect('so.db')
>>> c = conn.cursor()

rows的数量:

>>> c.execute('''select count(*) from data''').next()
(4,)

name搜索:

>>> c.execute('''select * from data where name="Paul"''').fetchall()
[(u'Paul', 22, u'Car Dealer')]
>>> c.execute('''select * from data where name="qwerty"''').fetchall()
[]

age搜索:

>>> c.execute('''select * from data where age="66"''').fetchall()
[(u'Mark', 66, u'Retired')]

occupation搜索:

>>> c.execute('''select * from data where occupation="Engineer"''').fetchall()
[]
>>> c.execute('''select * from data where occupation="Doctor"''').fetchall()
[(u'Nick', 30, u'Doctor')]

如果您只想nextTrue作为输出,请使用False

>>> bool(next(c.execute('''select * from data where age=36'''), 0))
False
>>> bool(next(c.execute('''select * from data where age=66'''), 0))
True

c.fetchall()将返回所有匹配的行。