在 Python 中查詢列表列表中每個位置給定字元的頻率


讓我們考慮一個場景,您有一個列表,其中包含列表作為其元素。我們有興趣在內部列表的不同位置查詢一個字元的頻率。下面的示例將闡明需求。

考慮下面給出的列表列表。

listA = [['a', 'a', 'b'],
['a', 'c', 'b'],
['c', 'a', 'b'],
['c', 'a', 'a']]

在上面的列表中,我們有元素,它們是包含 3 個元素的列表。如果我考慮第一個內部列表,它在位置 0、1、2 處具有 a、a、b。類似地,對於第 3 個列表,它在 0、1、2 處為 c、a、b。考慮到所有內部列表,我們可以說位置 0 處 a 的頻率為 2,位置 1 處為 3,位置 2 處為 1。

下面的程式旨在為列表列表中的任何元素查詢此類值。

使用 pandas

pandas 庫被廣泛用於透過建立資料幀來進行資料操作。因此,我們建立一個數據幀並使用 where 子句迴圈遍歷它,以查詢資料幀中每個位置是否存在值“a”。

示例

 線上演示

import pandas as pd

# Given list of lists
listA = [['a', 'a', 'b'],
['a', 'c', 'b'],
['c', 'a', 'b'],
['c', 'a', 'a']]

# using pandas
df = pd.DataFrame(listA)
res = df.where(df == 'a', 0).where(df != 'a', 1)

# Result
print("Occurrence of 'a' at 0,1 and 2 position\n", res.sum())

輸出

執行以上程式碼會得到以下結果:

Occurrence of 'a' at 0,1 and 2 position
0 2.0
1 3.0
2 1.0

使用 zip

我們可以使用 for 迴圈遍歷列表中子列表中的每個位置,並將 zip 函式應用於整個列表列表。

示例

 線上演示

# Given list of lists
listA = [['a', 'a', 'b'],
['a', 'c', 'b'],
['c', 'a', 'b'],
['c', 'a', 'a']]

res = [elem.count('a') for elem in zip(*listA)]
# Result
print("Occurrence of 'a' at 0,1 and 2 position\n", res)

輸出

執行以上程式碼會得到以下結果:

Occurrence of 'a' at 0,1 and 2 position
[2, 3, 1]

更新於: 2020-05-05

194 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.