我有一個功能,我寫了從2D列表(從CSV上傳)刪除列:KeyError:0; Python從列表中刪除列
#method to remove a column from a list if it does not contain an int
def remove_nonint(list):
for row in list:
for i in range(0, len(row)):
if isinstance(row[i], (int, long)) != True:
del row[i]
然而,當我在名單上運行此,我得到以下錯誤:
<ipython-input-23-10a39a11efb3> in remove_nonint(list)
3 for row in list:
4 for i in range(0, len(row)):
----> 5 if isinstance(row[i], (int, long)) != True:
6 del row[i]
KeyError: 0
列表[0]是這樣的:
{u'2B': 0,
u'3B': 0,
u'AB': 4,
u'BB': 0,
u'CS': 0,
u'G': 1,
u'GIDP': None,
u'H': 0,
u'HBP': None,
u'HR': 0,
u'IBB': None,
u'R': 0,
u'RBI': 0,
u'SB': 0,
u'SF': None,
u'SH': None,
u'SO': 0,
u'lgID': u'NA',
u'playerID': u'abercda01',
u'stint': u'1',
u'teamID': u'TRO',
u'yearID': u'1871'}
編輯:這是我上傳的CSV:
import unicodecsv
with open('lahman-csv_2015-01-24/batting.csv', 'rb') as f:
reader = unicodecsv.DictReader(f)
batting = list(reader)
batting[0]
它是一個二維列表或類型的字典列表? –
也許你想要改變'對於我在範圍內(0,len(row)):'to'鍵入行:'? – user2829759
我用DictReader,所以我想它是一個字典列表 – user1072337