簡體   English   中英

如何在python中操作列表

[英]How to manipulate lists in python

我有一個看起來像這樣的清單

[(u'will', 332), (u'Indian', 398), (u'#AAP', 409), (u'Rahul', 430), (u'Modi', 441)]

我想使用Google圖表將其繪制在條形圖上。 Google需要以下格式的數據-

[
['Year', 'Austria'],
['2003',  1336060],
['2004',  1538156],
['2005',  1576579],
['2006',  1600652],
['2007',  1968113],
['2008',  1901067]

]

如何將清單轉換成這種格式? 我知道我可以說list.add在第一個位置添加標題。 但是,如何更改列表的其余部分? 如果您想知道我是怎么得到這種格式的列表的,請使用以下代碼:

f = open('data/convertcsv.json')
        data = json.loads(f.read())
        f.close()
        wordDict = {}
        for row in data:
            # print row['sentiment']
            wordList = row['text'].split()
            for word in wordList:
                if len(word) < 4: continue
                if word in wordDict: wordDict[word] += 1
                else: wordDict[word] = 1
        sorted_list = sorted(wordDict.iteritems(), key=operator.itemgetter(1))
        final_list = sorted_list[-5:]

您是否嘗試只是json.dumps您的列表? 格式已經正確(將元組轉換為JSON數組就可以了)。

您需要做的就是添加標題(使用insert ,但不add

對於您是否在使用Python數據結構還是僅在導出到JSON時遇到問題,我尚不完全清楚。 無論如何,如果要使現有數據看起來像示例一樣,您要做的就是:

original_data = [(u'will', 332), (u'Indian', 398), (u'#AAP', 409), (u'Rahul', 430), (u'Modi', 441)]

reworked_data = [['x_label', 'y_label']]

for item in original_data:
    reworked_data.append(list(item))

reworked_data
Out[4]: 
[['x_label', 'y_label'],
 [u'will', 332],
 [u'Indian', 398],
 [u'#AAP', 409],
 [u'Rahul', 430],
 [u'Modi', 441]]

要導出為JSON,您可以執行以下操作:

json.dumps(reworked_data)
Out[6]: '[["x_label", "y_label"], ["will", 332], ["Indian", 398], ["#AAP", 409], ["Rahul", 430], ["Modi", 441]]'

但是正如Matti所說,不必將元組轉換為列表即可,只需將標頭/標簽插入原始列表即可。

暫無
暫無

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

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