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

また、上記の 2 行を 1 つにまとめることはできますか?


組み込み関数を使用:

  • 名前が存在するかどうかを見つけるために、最初の列で名前を検索するにはどうすればよいですか?

  • 値が存在する場合、テーブル全体を検索するにはどうすればよいですか?

4

4 に答える 4

4

ポールが指摘したように:

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

他の 2 つの質問については、これがビルトインに最も近いものです。

>>> '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 に答える
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必要に応じTrueFalse出力として使用します。

>>> 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 に答える