0

假设我有一个名为“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

4 回答 4

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
于 2013-09-03T16:13:32.003 回答
3

你想使用len内置:

f = len(a)
于 2013-09-03T16:00:43.877 回答
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
于 2013-09-03T16:15:32.123 回答
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')]

next如果您只想True作为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()将返回所有匹配的行。

于 2013-09-03T17:00:38.950 回答