簡體   English   中英

如何從 Python 中的列表中刪除括號?

[英]How to remove the brackets from list in Python?

我有一個清單:

list1 = ['[0', '"properties"', '"ipv4"', '0', '"value"]']

我想要輸出:

list1= 0 , "properties" , "ipv4" , 0 , "value"

我試過了:

ini_string = ini_string.replace('[', '').replace(']','')

但它給出了如下輸出:

> 0 
> query_json2 = query_json2[ini_string] TypeError: list indices must be integers or slices, not str

嘗試這個...

list1 = ['[0', '"properties"', '"ipv4"', '0', '"value"]']
a = [a.replace('[', '').replace(']', '') for a in list1]
b = ', '.join(a)
print(b)

讓我們假設您是否通過字典進行迭代。 所以在上面的代碼之后。

some_dict = {
    0: {
        'properties': {
            'ipv4': {
                0: {
                    'value': 'new_value'
                }
            }
        }
    }
}

for x in a:
    if x.isdigit():
        new = some_dict[int(x)]
    else:
        x = x.replace('"', '')
        new = some_dict[x]
    some_dict = new


print(some_dict)
import re
result = ''
for word in list1:
  cleanWord = ''.join(re.split('[|]'))
  result += cleanWord + ' ,'
print("list 1 = " + result[:-2])

本質上,您將其從[]剝離,並將其附加到字符串以輸出

試試這個....

list1 = ['[0', '"properties"', '"ipv4"', '0', '"value"]']
for i in range(0,len(list1)):
    if "[" in list1[i] or "]" in list1[i]:
        list1[i] = re.sub(r'[^\w]', '', list1[i])
print(",".join(list1))```

暫無
暫無

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

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