簡體   English   中英

如果列表在 Python 中,如何迭代列表?

[英]How to iterate over a list if lists in Python?

我有這個清單:

my_list = [['ga:date'], ['ga:country', 'ga:date'], ['ga:country', 'ga:date']]

並嘗試對其進行迭代以獲取值及其位置,如下所示:

date    1
country 1
date    2
country 1
date    2

它應該稍后存儲在熊貓 df 中,值可以不同,沒有修復。

最初它是一個字典列表:

my_original_list = [
    [{'name': 'ga:date'}],
    [{'name': 'ga:country'}, {'name': 'ga:date'}],
    [{'name': 'ga:country'}, {'name': 'ga:date'}]
]

# But I got the values out of it in a list:
my_list = [li['name'] for li in my_original_list]

# the result
my_list = [
    ['ga:date'], 
    ['ga:country', 'ga:date'],
    ['ga:country', 'ga:date']
]

已經破解我的想法如何得到它,將不勝感激任何幫助

對元組列表使用帶有enumerate和展flattening列表理解:

my_list = [['ga:date'], ['ga:country', 'ga:date'], ['ga:country', 'ga:date']]

x = [(b, a) for i in my_list for (a, b) in enumerate(i, 1)]
print (x)
[('ga:date', 1), ('ga:country', 1), ('ga:date', 2), ('ga:country', 1), ('ga:date', 2)]

df = pd.DataFrame(x, columns = ['field','listIndex'])
print (df)
        field  listIndex
0     ga:date          1
1  ga:country          1
2     ga:date          2
3  ga:country          1
4     ga:date          2

或者如果可能的話改變列的位置:

x1 = [z for i in my_list for z in enumerate(i, 1)]
print (x1)
[(1, 'ga:date'), (1, 'ga:country'), (2, 'ga:date'), (1, 'ga:country'), (2, 'ga:date')]

df = pd.DataFrame(x1, columns = ['listIndex','field'])
print (df)
   listIndex       field
0          1     ga:date
1          1  ga:country
2          2     ga:date
3          1  ga:country
4          2     ga:date

此外,如果需要在:之前刪除值:

my_list = [['ga:date'], ['ga:country', 'ga:date'], ['ga:country', 'ga:date']]

x = [(b.split(':')[-1], a) for i in my_list for (a, b) in enumerate(i, 1)]
print (x)
[('date', 1), ('country', 1), ('date', 2), ('country', 1), ('date', 2)]

df = pd.DataFrame(x, columns = ['field','listIndex'])
print (df)
     field  listIndex
0     date          1
1  country          1
2     date          2
3  country          1
4     date          2

您可以為此使用枚舉:

my_list = [['ga:date'], ['ga:country', 'ga:date'], ['ga:country', 'ga:date']]

for sublist in my_list:
    for position, entry in enumerate(sublist):
        print(entry, position + 1)  # +1 to count positions starting at 1 instead of 0.

這個怎么樣?

import pandas

my_list = [['ga:date'], ['ga:country', 'ga:date'], ['ga:country', 'ga:date']]
df = pandas.DataFrame(data=[(sublist[i],i) for sublist in my_list for i in range(len(sublist))], columns=["field", "listIndex"])

結果:

        field  listIndex
0     ga:date          0
1  ga:country          0
2     ga:date          1
3  ga:country          0
4     ga:date          1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM