Hướng dẫn python transform list
Show Có một vài lời khuyên hữu ích để chuyển đổi Python list (hoặc bất kỳ danh sách lặp nào khác như tuple) thành string. Đầu tiên, Bizfly Cloud chia sẻ danh sách các string, bạn chỉ cần thực hiện cách này: >>> mylist = ['spam', 'ham', 'eggs'] >>> print ', '.join(mylist) spam, ham, eggs Sử dụng cùng một phương pháp, bạn cũng có thể làm điều này: >>> print '\n'.join(mylist) spam ham eggs Tuy nhiên, phương pháp đơn giản này không hoạt động nếu danh sách chứa các đối tượng không phải chuỗi, chẳng hạn như số nguyên. Nếu bạn chỉ muốn có comma-separated string (chuỗi được phân cách bằng dấu phẩy), bạn có thể sử dụng lối tắt này: >>> list_of_ints = [80, 443, 8080, 8081] >>> print str(list_of_ints).strip('[]') 80, 443, 8080, 8081 Hoặc lệnh này,
nếu đối tượng của bạn chứa dấu ngoặc vuông: >>> print str(list_of_ints)[1:-1] 80, 443, 8080, 8081 Cuối cùng, bạn có thể sử dụng map() để chuyển đổi từng mục trong danh sách thành một chuỗi và sau đó nối chúng: >>> print ', '.join(map(str, list_of_ints)) 80, 443, 8080, 8081 >>> print '\n'.join(map(str, list_of_ints)) 80 443 8080 8081 Chúc các bạn thành công! Theo Bizfly Cloud chia sẻ >> Có thể bạn quan tâm: Hướng dẫn liệt kê bảng ARP trên ESXi với esxcli View Discussion Nội dung chính
Improve Article Save Article View Discussion Improve Article Save Article Sometimes, while working with list, we can have a wish to have each of element of list to be converted or unpacked into required variables. This problem can occur in web development domain. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using
Output : The original list is : [1, 3, 7, 4, 2] Variables as assigned are : 1 3 7 4 2 Method #2 : Using Namedtuple
Output : The original list is : [1, 3, 7, 4, 2] Variables as assigned are : 1 3 7 4 2 How do you convert a list into a variable?Method #1 : Using "=" operator This task can be performed using a “=” operator. In this we just ensure enough variables as the count of list elements and assign them to list, the list elements get allotted to variables in order of their assignment. How do you convert a list in Python?Typecasting to list can be done by simply using list(set_name) . Using sorted() function will convert the set into list in a defined order. Can U turn a list into a string?To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output. Can you make a list of variables in Python?Since a list can contain any Python variables, it can even contain other lists. |