开发者社区> 问答> 正文

类型错误:字符串索引必须是整数—Python中的列表和字典[关闭]

我有一个名为df_following的列表,它看起来像这样:

[('henrysimanjun13',                          following
  henrysimanjun13  [AndiDar59797467]), ('hamdalah47', Empty DataFrame
  Columns: []
  Index: []), ('vivoslot',                                         following
  vivoslot  [AprillParis, liputan6dotcom, detikcom]), ('KacangTopless',
                                            following
  KacangTopless  [mohmahfudmd, CallMeNayr, siti_dama]), ('infosantuy1',
                                                       following
  infosantuy1  [OneLouderApps, DakwahJateng, setkabgoid, okez...)]

print ("df_following[0]: ", df_following[0][0])
--> df following[0]: buin83
print ("df_following[0]: ", df_following[0][1]['following'][0][0]) 
--> df following[0]: AkuDutaDamai

从上面的列表中,我想做出这样的东西:

{buin83, AkuDutaDamai},{buin83, FarlinaYaz}, {buin83, Mom_isback}, {buin83, yosiago}, {killjoyyadi, susipudjiastuti}, {killjoyyadi, PetrusBun},..

我试着:

d = {}

for l in df_following:
    username = l[0][0]
    following = l[0][1]['following'][0][0]

    if username in d: 
        d[username][following] = [following]
    else: 
        d[username] = {username,following}

但我得到以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-135-437589d2001c> in <module>
      3 for l in df_following:
      4     username = l[0][0]
----> 5     following = l[0][1]['following'][0][0]
      6 
      7     if username in d:

TypeError: string indices must be integers

我不知道我的代码出了什么问题。任何建议吗? 问题来源StackOverflow 地址:/questions/59386757/typeerror-string-indices-must-be-integers-lists-and-dictionary-in-python

展开
收起
kun坤 2019-12-25 21:52:11 915 0
0 条回答
写回答
取消 提交回答
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载