Hướng dẫn how do i convert a string to a list in brackets in python? - làm cách nào để chuyển đổi chuỗi thành danh sách trong ngoặc trong python?

Không cần nhập bất cứ thứ gì hoặc để đánh giá. Bạn có thể làm điều này trong một dòng cho hầu hết các trường hợp sử dụng cơ bản, bao gồm cả trường hợp được đưa ra trong câu hỏi ban đầu.

Lót

l_x = [i.strip() for i in x[1:-1].replace('"',"").split(',')]

Giải trình

x = '[ "A","B","C" , " D"]'
# String indexing to eliminate the brackets.
# Replace, as split will otherwise retain the quotes in the returned list
# Split to convert to a list
l_x = x[1:-1].replace('"',"").split(',')

Outputs:

for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4

Bạn có thể phân tích và làm sạch danh sách này khi cần thiết bằng cách sử dụng danh sách hiểu.

l_x = [i.strip() for i in l_x] # list comprehension to clean up
for i in range(0, len(l_x)):
    print(l_x[i])
# vvvvv output vvvvv
'''
A
B
C
D
'''

Danh sách lồng nhau

Nếu bạn có danh sách lồng nhau, nó sẽ khó chịu hơn một chút. Nếu không sử dụng regex (điều này sẽ đơn giản hóa việc thay thế) và giả sử bạn muốn trả lại một danh sách dẹt (và Zen of Python nói rằng căn hộ tốt hơn so với lồng nhau):

x = '[ "A","B","C" , " D", ["E","F","G"]]'
l_x = x[1:-1].split(',')
l_x = [i
    .replace(']', '')
    .replace('[', '')
    .replace('"', '')
    .strip() for i in l_x
]
# returns ['A', 'B', 'C', 'D', 'E', 'F', 'G']

Nếu bạn cần giữ lại danh sách lồng nhau, nó sẽ trở nên xấu hơn một chút, nhưng nó vẫn có thể được thực hiện chỉ với các biểu thức thông thường và danh sách hiểu:

import re

x = '[ "A","B","C" , " D", "["E","F","G"]","Z", "Y", "["H","I","J"]", "K", "L"]'
# Clean it up so the regular expression is simpler
x = x.replace('"', '').replace(' ', '')
# Look ahead for the bracketed text that signifies nested list
l_x = re.split(r',(?=\[[A-Za-z0-9\',]+\])|(?<=\]),', x[1:-1])
print(l_x)
# Flatten and split the non nested list items
l_x0 = [item for items in l_x for item in items.split(',') if not '[' in items]
# Convert the nested lists to lists
l_x1 = [
    i[1:-1].split(',') for i in l_x if '[' in i
]
# Add the two lists
l_x = l_x0 + l_x1

Giải pháp cuối cùng này sẽ hoạt động trong bất kỳ danh sách nào được lưu trữ dưới dạng chuỗi, lồng nhau hay không.

Trong bài học này, bạn sẽ khám phá các phương thức chuỗi chuyển đổi giữa một chuỗi và một số loại dữ liệu tổng hợp bằng cách dán các đối tượng lại với nhau để tạo một chuỗi hoặc bằng cách chia một chuỗi thành từng mảnh. Các phương thức này hoạt động trên hoặc trả về Iterables, thuật ngữ Python chung cho một bộ sưu tập các đối tượng tuần tự.string methods that convert between a string and some composite data type by either pasting objects together to make a string, or by breaking a string up into pieces. These methods operate on or return iterables, the general Python term for a sequential collection of objects.

Nhiều phương pháp trong số này trả về một danh sách hoặc một tuple. Một danh sách bao gồm bộ sưu tập các đối tượng trong ngoặc vuông (

x = '[ "A","B","C" , " D"]'
# String indexing to eliminate the brackets.
# Replace, as split will otherwise retain the quotes in the returned list
# Split to convert to a list
l_x = x[1:-1].replace('"',"").split(',')
2) và có thể thay đổi. Một tuple bao quanh các đối tượng của nó trong ngoặc đơn (
x = '[ "A","B","C" , " D"]'
# String indexing to eliminate the brackets.
# Replace, as split will otherwise retain the quotes in the returned list
# Split to convert to a list
l_x = x[1:-1].replace('"',"").split(',')
3) và là bất biến.

Dưới đây là các phương pháp chuyển đổi giữa các chuỗi và danh sách:

  • x = '[ "A","B","C" , " D"]'
    # String indexing to eliminate the brackets.
    # Replace, as split will otherwise retain the quotes in the returned list
    # Split to convert to a list
    l_x = x[1:-1].replace('"',"").split(',')
    
    4
  • x = '[ "A","B","C" , " D"]'
    # String indexing to eliminate the brackets.
    # Replace, as split will otherwise retain the quotes in the returned list
    # Split to convert to a list
    l_x = x[1:-1].replace('"',"").split(',')
    
    5
  • x = '[ "A","B","C" , " D"]'
    # String indexing to eliminate the brackets.
    # Replace, as split will otherwise retain the quotes in the returned list
    # Split to convert to a list
    l_x = x[1:-1].replace('"',"").split(',')
    
    6
  • x = '[ "A","B","C" , " D"]'
    # String indexing to eliminate the brackets.
    # Replace, as split will otherwise retain the quotes in the returned list
    # Split to convert to a list
    l_x = x[1:-1].replace('"',"").split(',')
    
    7
  • x = '[ "A","B","C" , " D"]'
    # String indexing to eliminate the brackets.
    # Replace, as split will otherwise retain the quotes in the returned list
    # Split to convert to a list
    l_x = x[1:-1].replace('"',"").split(',')
    
    8
  • x = '[ "A","B","C" , " D"]'
    # String indexing to eliminate the brackets.
    # Replace, as split will otherwise retain the quotes in the returned list
    # Split to convert to a list
    l_x = x[1:-1].replace('"',"").split(',')
    
    9

Đây là cách sử dụng

for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4
0:

>>>

>>> mylist = ['spam', 'egg', 'sausage', 'bacon', 'lobster']
>>> mylist
['spam', 'egg', 'sausage', 'bacon', 'lobster']

>>> '; '.join(mylist)
'spam; egg; sausage; bacon; lobster'
>>> ','.join(mylist)
'spam,egg,sausage,bacon,lobster'

>>> word = 'lobster'
>>> type(word)

>>> ':'.join(word)
'l:o:b:s:t:e:r'

>>> mylist2 = ['spam', 23, 'egg']
>>> type(mylist2)

>>> ', '.join(mylist2)
Traceback (most recent call last):
  File "", line 1, in 
    ', '.join(mylist2)
TypeError: sequence item 1: expected str instance, int found

>>> mylist3 = ['spam', str(23), 'egg']
>>> ', '.join(mylist3)
'spam, 23, egg'

Đây là cách sử dụng

for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4
1:

>>>

>>> s = 'egg.spam'
>>> s.partition('.')
('egg', '.', 'spam')

>>> t = 'egg$$spam$$bacon'
>>> t.partition('$$')
('egg', '$$', 'spam$$bacon')

Đây là cách sử dụng

for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4
1:

>>>

>>> t = 'egg$$spam$$bacon'
>>> t.rpartition('$$')
('egg$$spam', '$$', 'bacon')

>>> t.partition('.')
('egg$$spam$$bacon', '', '')

>>> t.rpartition('.')
('', '', 'egg$$spam$$bacon')

Đây là cách sử dụng

for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4
1:

>>>

>>> s = 'spam bacon sausage egg'
>>> s.split()
['spam', 'bacon', 'sausage', 'egg']

>>> s = 'spam\tbacon\nsausage egg'
>>> s.split()
['spam', 'bacon', 'sausage', 'egg']

>>> t = 'spam.bacon.sausage.egg'
>>> t.split('.')
['spam', 'bacon', 'sausage', 'egg']

>>> t = 'bacon...lobster...bacon'
>>> r.split('.')
['bacon', '', '', 'lobster', '', '', 'bacon']

>>> q = 'bacon\n lobster\t\n egg'
>>> q.split()
['bacon', 'lobster', 'egg']

>>> link = 'www.realpython.com'
>>> link.split('.', maxsplit=1)
['www', 'realpython.com']

Đây là cách sử dụng

for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4
1:

>>>

x = '[ "A","B","C" , " D"]'
# String indexing to eliminate the brackets.
# Replace, as split will otherwise retain the quotes in the returned list
# Split to convert to a list
l_x = x[1:-1].replace('"',"").split(',')
0

Đây là cách sử dụng

for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4
1:

>>>

x = '[ "A","B","C" , " D"]'
# String indexing to eliminate the brackets.
# Replace, as split will otherwise retain the quotes in the returned list
# Split to convert to a list
l_x = x[1:-1].replace('"',"").split(',')
1

Đây là cách sử dụng for i in range(0, len(l_x)): print(l_x[i]) # vvvv output vvvvv ''' A B C D ''' print(type(l_x)) # out: class 'list' print(len(l_x)) # out: 4 1:

Đây là cách sử dụng
for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4
2:We can convert it to the list of characters using list() built-in function. When converting a string to list of characters, whitespaces are also treated as characters.

Chúng tôi sử dụng khung nào cho danh sách trong Python?

Trong Python, các danh sách được đặt hàng các bộ sưu tập các mục cho phép sử dụng dễ dàng một bộ dữ liệu.Các giá trị danh sách được đặt ở giữa dấu ngoặc vuông [], được phân tách bằng dấu phẩy.square brackets [ ] , separated by commas.