无法从python列表中获得所需的输出

时间:2019-09-26 14:58:22

标签: python

我下面的python代码有一个小问题。 我有一个包含以下元素的列表。此列表也可以为空,没有内容。

如您所见,This is my first stock I bought 01.27.2019已编码,我必须对其进行解码才能删除b''。当我在mylist上执行分割操作时,我将''作为列表中的第一项,但不确定为什么。

mylist = "$17$b'This is my first stock I bought 01.27.2019'"
The fields in mylist are seperated by a $ rather than a ,
        tmp_list = mylist.split('$')
        print (tmp_list) # ['', '17', "b'This is my first stock I bought 01.27.2019'"] ---> Not sure why I have the '' as the first item in the tmp_list
        tmp_iter = iter(tmp_list)
        res['myinfo']= '{' + '},{'.join(f'{n},{s}' for n, s in zip(tmp_iter, tmp_iter)) + '}'

我希望我的res['myinfo']"{{17, This is my first stock I bought 01.27.2019}, ...many more {,}}

有时,res['myinfo']可能只是mylist = [""]

我不确定如何修复我的代码,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

首先

mylist = "$17$b'This is my first stock I bought 01.27.2019'"

应该是

mylist = "17$b'This is my first stock I bought 01.27.2019'"

就像@takendarkk所说的

  

这可能是因为字符串中的第一个字符是您的   分隔符($)。在那之前呢?没有。 – Takedarkk

对于解码字符串,假设它们都类似:“ b' 一些字符串 ' “,并且必须在年龄之前解码列表中的所有奇数索引元素。一个非常严格的解决方案可能是:

def decodeString(stringToDecode):
    decodedList = []
    for i in range(2, len(stringToDecode)-1):  #every character except the first 2 and the last one
        decodedList.append(stringToDecode[i])
    decodedString = ''.join(decodedList)
    return decodedString

for i in range(len(tmp_list)):
    if i % 2 == 1:                                 #every odd indexed element
        decodedString = decodeString(tmp_list[i])
        tmp_list[i] = decodedString

似乎您在这里还需要一层“ {}”:

res['myinfo']= '{' + '},{'.join(f'{n},{s}' for n, s in zip(tmp_iter, tmp_iter)) + '}'

通过这种方式,您的res['myinfo']{17,This is my first stock I bought 01.27.2019},{18,This is my second stock I bought 01.28.2019},但如果您想像自己所说的那样'{{17,This is my first stock I bought 01.27.2019},{18,This is my second stock I bought 01.27.2019}}',则需要:

res['myinfo']= '{' + '{' + '},{'.join(f'{n},{s}' for n, s in zip(tmp_iter, tmp_iter)) + '}' + '}'