Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to convert between lists, tuples, dictionaries and collections in Python

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article focuses on "how to convert lists, tuples, dictionaries and collections in Python". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to convert lists, tuples, dictionaries and collections in Python.

Front row tip: Yuanzu is written in the wrong way (with typos), some articles are written as Yuanzu errors, and the correct statement is tuple.

First of all, understand the sequence.

A sequence is a group of elements that have a sequential relationship. It is an one-dimensional element vector, and element types can be different.

Elements are guided by sequence numbers and specific elements of the sequence are accessed through subscripts.

Sequence is a base class type, and tuple and list are an extension of sequence type, which inherits all common operations of sequence type.

(1) set set

A set is a collection of our mathematics, and the best application of a set is to remove duplicates-all elements of the set type are not duplicated. Collections can be created using {} or set ().

Note: print ends with a newline character by default, while end= "" ends print with a space character.

(2) tuple tuple

There is no structural difference between tuples and lists (because tuples and lists are an extension of sequence types), the only difference is that tuples are read-only and cannot be modified after creation.

Therefore, there is an application scenario-data protection: if you do not want the data to be changed by the program, convert to a tuple type.

Tuples are created using parentheses () or tuple (). You can use parentheses or not.

(3) list list

What is a list? I think the list is the list that we often see in our daily life.

For example, counting the things we bought in the past week and making a list of these things is a list.

Since we may buy something more than once, duplicates are allowed in the list.

If we expand the scope of the list and count all our spending over the past week, then this is also a list, but there will be different categories of items in this list, such as we buy things as a kind of cost, and paying utilities is also a kind of expense. the types of these items can make a difference.

Python lists are the same as lists, except that they are repeatable and of different types. Different types are also the most essential difference from arrays.

The list can be modified at will after it is created (tuples are not allowed). The list in python is created with [] or list ():

(4) the dictionary dict

The last one is a dictionary. The dictionary type is the embodiment of "mapping".

A dictionary is a collection of key-value pairs, which are out of order.

Created with curly braces {} and dict (), key-value pairs are represented by colons:.

The greatest value of the dictionary is the query, through the key, to find the value.

Here are some small examples

1. List tuples to other

# list to set (deduplicated) list1 = [6, 7, 7, 8, 8, 9] set (list1) # {6, 7, 8, 9} # two list to dictionary list1 = ['key1','key2','key3'] list2 = [' 1 'dict (list1,list2)] dict (zip (list1,list2)) # {' key1':'1 'key3':' 3'} # nested list to dictionary list3 = [['key1','value1'], [' key2','value2'], ['key3','value3']] dict (list3) # {' key1': 'value1',' key2': 'value2',' key3': 'value3'} # list, tuple to string list2 = [' a','a' 'b'] '.join (list2) #' aab' tup1 = ('asides,' asides,'b')''.join (tup1) #' aab

2. Change the dictionary to others

# Dictionary is converted to the string dic1 = {'value:key for key, value in a_dict.items ()} 2} str (dic1) # "{'afiuvahuanglu 1magistrate value 2}" # Dictionaries key and value convert each other to dic2 = {' axiafiug 1, 'value:key for key: 3} {value:key for key, value in a_dict.items ()} # {1:' ajar, 2: 'baked, 3:' c'}

3. Transfer the string to other

# string rotation list s = 'aabbcc'list (s) # [' averse, 'baked,' clocked,'c'] # string transfer tuple tuple (s) # ('averse,' averse, 'baked,' baked, 'clocked,' c') # string transfer set set (s) # {'aqu,' b' 'c'} # string conversion dictionary dic2 = eval ("{'name':'ljq',' age':24}") # Segmentation string a ='a b c'a.split ('') # ['a', 'baked,' c'] dictionary splitting and merging

Split:

Base = {'key, base [key]) for key in subkey]) print (subdict)-- {' Clipper V3, 'Elevanza 5} print

Merge:

Method 1:

D1 = {'user':'root','pwd':'1234'} D2 = {' ip':'127.0.0.1','port':8080} d3=dict (D1, * * D2) print (D3)

Method 2:

D1 = {'user':'root','pwd':'1234'} d2 = {' ip':'127.0.0.1','port':8080} d3 = {} for kpene v in d1.items (): D3 [k] = vfor kpene v in d2.items (): D3 [k] = vprint (d3) list Segmentation and merging a = [1pr 2je 3je 4je 5je 6] b = ['afei d'] print (aqb) a = [1MJ 2JI 3JI] 5 print 6] b = [1) a+=bprint (a) a = [1, 2, 3, 4, 5, 5, and 6] b = [a.extend (b) print (a) a = [1, 2, 4, 5, 5, and 6] b = [a, 2, 4, 5, and 6] b = [0:0] a [0:0] = bprint (a) li = [ '.join (li) res2=''.join (res1) .split (';') at this point, I believe you have a better understanding of "how to convert lists, tuples, dictionaries, and collections in Python". Let's do it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report