Python:无法修复解析列表中的错误

时间:2015-09-23 06:32:44

标签: python list

我有一个看起来像这样的python代码。

trades = self.get_trades(socket)  # returns a 2D list
print trades              #this prints the list
for trade in trades :
    print trade           # prints each row in list

print trades行打印出一个实际上看起来像这样的2d

[['name_1_1_D', '150923000048067', 'NIFTY15SEP7800CE', 'SELL', 'MKT', 25, 0, 36.
7], ['name_2_1_3', '150923000048824', 'NIFTY15SEP7800CE', 'BUY', 'MKT', 25, 0, 3
5.8], ['name_3_1_M', '150923000049331', 'NIFTY15SEP7800CE', 'BUY', 'MKT', 25, 0,
 36.55], ['name_4_1_E', '150923000049744', 'NIFTY15SEP7800CE', 'SELL', 'MKT', 25
, 0, 36.6], ['name_5_1_5', '150923000051339', 'NIFTY15SEP7800CE', 'BUY', 'MKT',
25, 0, 40.4], ['name_6_1_Q', '150923000052013', 'NIFTY15SEP7800CE', 'SELL', 'MKT
', 25, 0, 38.1]]

但是在打印单个List元素时,for循环print trade内的行正在打印一个错误的元素

['name_1_1_D', '150923000048067', 'NIFTY15SEP7800CE', 'SELL', '', 25, 0, 0.0]

列表的第5和第8个元素已更改为''和0.0。

我真的没有理解为什么会发生这种事情以及我的代码的哪一部分是错误的。任何帮助,将不胜感激。

3 个答案:

答案 0 :(得分:1)

在python 2.9.10中也可以正常工作:

trades = [['name_1_1_D', '150923000048067', 'NIFTY15SEP7800CE','SELL', 'MKT', 25, 0, 36.7],
          ['name_2_1_3', '150923000048824', 'NIFTY15SEP7800CE', 'BUY', 'MKT', 25, 0, 35.8],
          ['name_3_1_M', '150923000049331', 'NIFTY15SEP7800CE', 'BUY', 'MKT', 25, 0, 36.55],
          ['name_4_1_E', '150923000049744', 'NIFTY15SEP7800CE', 'SELL', 'MKT', 25 , 0, 36.6],
          ['name_5_1_5', '150923000051339', 'NIFTY15SEP7800CE', 'BUY', 'MKT', 25, 0, 40.4],
          ['name_6_1_Q', '150923000052013', 'NIFTY15SEP7800CE', 'SELL', 'MKT ', 25, 0, 38.1]]

print trades

for trade in trades:
    print trade

答案 1 :(得分:1)

我认为来自套接字的数据流中有换行符 显然,只需输入您的数据并运行代码,就不会复制您所拥有的情况 测试数据以查找来自套接字的数据中的多余字符。

答案 2 :(得分:0)

在python 3.4.3下工作正常:

脚本run.py

trades = [['name_1_1_D', '150923000048067', 'NIFTY15SEP7800CE', 'SELL', 'MKT', 25, 0, 36.7], ['name_2_1_3', '150923000048824', 'NIFTY15SEP7800CE', 'BUY', 'MKT', 25, 0, 35.8], ['name_3_1_M', '150923000049331', 'NIFTY15SEP7800CE', 'BUY', 'MKT', 25, 0, 36.55], ['name_4_1_E', '150923000049744', 'NIFTY15SEP7800CE', 'SELL', 'MKT', 25, 0, 36.6], ['name_5_1_5', '150923000051339', 'NIFTY15SEP7800CE', 'BUY', 'MKT',25, 0, 40.4], ['name_6_1_Q', '150923000052013', 'NIFTY15SEP7800CE', 'SELL', 'MKT', 25, 0, 38.1]]

for trade in trades:
    print(trade)

Exacution:

$ python run.py
['name_1_1_D', '150923000048067', 'NIFTY15SEP7800CE', 'SELL', 'MKT', 25, 0, 36.7]
['name_2_1_3', '150923000048824', 'NIFTY15SEP7800CE', 'BUY', 'MKT', 25, 0, 35.8]
['name_3_1_M', '150923000049331', 'NIFTY15SEP7800CE', 'BUY', 'MKT', 25, 0, 36.55]
['name_4_1_E', '150923000049744', 'NIFTY15SEP7800CE', 'SELL', 'MKT', 25, 0, 36.6]
['name_5_1_5', '150923000051339', 'NIFTY15SEP7800CE', 'BUY', 'MKT', 25, 0, 40.4]
['name_6_1_Q', '150923000052013', 'NIFTY15SEP7800CE', 'SELL', 'MKT', 25, 0, 38.1]