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 use square brackets, curly braces and parentheses in Python

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to use square brackets, curly braces and parentheses in Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Square bracket

Square brackets are the first symbol in almost all programming languages. The first here does not refer to the frequency of use, but to the connotation and creativity of the programming language shown by this symbol. In fact, square brackets may also be at the top of the list in terms of how often symbols are used-it's just my intuition, which is not supported by statistics.

1.1 create list

For beginners, the most common way to create a list is to use a square bracket.

> a = [] > > a [] > > b = [3.14, False,'x, None] > b [3.14, False,'x, None]

Even old birds use a lot of square brackets to create lists, especially if they use deductive ones.

> c = [ionization 2 for i in range (5)] > c [0,1,4,9,16]

But I have always thought that square brackets are like colloquial or slang, too casual. I prefer to use the rigorous list () to create lists. Creating lists using list () is the standard way to instantiate the list class, and you can see how the constructor of the list class adapts to different types of parameters.

> > a = list () > > a [] > > b = list ((3.14, False,'x, None)) > > b [3.14, False, 'Xerox, None] > c = list ({1pyrrine 3}) > d = list ({' xbike,'y','z'] > > e = list (range (5)) > > e 4] > f = list ('* * i for i in range (5)) > f ['','*','*'] 1.2 Index of the list

Square brackets can create lists, but square brackets are not the same as lists because square brackets are also used for indexing.

> > [3.14, False,'x, None] [2] x'> [3.14, False,'x, None] [- 2]'x'> [3.14, False,'x, None] [1:] [False,'x, None] > [3.14, False,'x, None] [:-1] [:-1] [3.14, False,'x'] > [3.14, False,'x, None] [: 2] [3.14 'x'] > [3.14, False,'x, None] [::-1] [None,'x, False, 3.14]

The index of the list is very flexible, especially the introduction of a negative index, using-1 to represent the last element or reverse order. The above operation, belongs to the common index method, if you can read the following code, it means that you have enough skills.

> a = [3.14, False,'x rays, None] > > a [2:2] = [1jre 2jue 3] > a [3.14, False, 1m 2pm 3,'x rays, None] 1.3 the method of listing

If the method of list object is readily available, it will be a master of Python.

> a = [3.14, False,'x, None] > a.index ('x') 2 > a.append ([1 ok', 2 False]) > > a [3. 14, False,'x, None, [1] > > a [- 1] .insert (1, 'ok',) > a [3.14, False,' x, None, [1, 'ok', 2]] > > a.remove (False) > > a [1, 'ok', 2,3] > a.pop (1)' x'> > a [3.14, None, [1, 'ok', 2,3]] > a.pop () [1,' ok', 2,3] > > a [3.14, None] 2. Curly braces

Curly braces represent dictionary objects, and most beginners think so. However, this is wrong, or at least one-sided. In the following code, both an and b are objects created with curly braces, but one is a dictionary and the other is a collection.

> > a = {} > > a {} > > b = {'x'> > b = {'x','x'} > type (a) > > type (b)

It turns out that Python uses curly braces to represent dictionary and collection objects: empty curly braces, or key-value pairs, represent dictionaries; curly braces have no repeating elements, indicating collections. To avoid misunderstanding, I am used to using dict () to generate dictionaries and set () to generate collections.

> > dict () {} > > dict ({'Xeroid dict 1,' yellowed dict 2, 'zonal dict 3}) {' Xerox dict: None, 'zoned dict: None ()' Xeroophore1), ('yearly dict.fromkeys: None) 'zonal: None} > dict.fromkeys (' abc', 0) {'aqian: 0, 'baked: 0,' caged: 0} > > set (3pence 4, 5)) {3pence 4pr 5} > > set ({'xprize 1,' yearly abc', 2, 'zonal abc', 3}) {' yellows, 'zoning,' x'} > set

In coding practice, although sets are irreplaceable in some cases, the frequency of collection is the lowest among the "four King Kong". Let's not discuss it here, just talk about the skills of using dictionaries.

2.1 determine whether a key exists in the dictionary

In the Py2 era, dict objects used to have a has_key () method to determine whether or not to contain a key. Py3 abandons this method to determine whether a key exists in the dictionary, and can only use a method such as in.

> a = dict ({'xtriple in aTrue 1,' yearly in aFalse2.2 2, 'zonal in aFalse2.2 3}) >' x' key >'v 'add a new key or update key value to the dictionary

Many people like to add a new key or update a key value to the dictionary by assigning a key to the dictionary.

> a = dict () > > a ['name'] =' xufive' > a {'name':' xufive'}

I don't recommend it. Using update () is more ceremonial, and you can add or modify more than one key at a time.

> a = dict () > > a.update ({'name':'xufive',' gender':''}) > a {'name':'xufive',' gender':''} 2.3 get a key from the dictionary

A ['age'] is the most common way, but it also encounters exceptions where the key does not exist. The following methods are recommended.

>

The dict class provides three methods, keys (), values (), and items (), that return all keys, all values, and all key-value pairs of the dictionary, respectively. It is important to note that the return result is not a list, but an iterator. If you need to return the results in the form of a list, use the list () conversion.

> a = dict () > > a.update ({'name':'xufive',' gender':' 'male'}) > list (a.keys ()) ['name',' gender'] > list (a.values ()) ['xufive',' male'] > list (a.items ()) [('name',' xufive'), ('gender',' male')]

When traversing dictionaries, many students write keys () as traversal dictionaries. In fact, it doesn't need to be so troublesome, it can be traversed directly like this.

> a = dict ([('name',' xufive'), ('gender',' male')] > for key in a: print (key, a [key]) name xufivegender male 3. Parentheses

Parentheses represent tuple objects, so it should be okay to say that? Indeed, it doesn't sound like a problem, but in the use of tuples, I believe every beginner will fall into the same pit at least once.

3.1 must enter the shallow pit

The most striking feature that tuples are not used for lists is that the value of an element cannot be updated. If you forget or ignore this point, you will fall into the pit.

> a = (3,4) > > a [0] = 5Traceback (most recent call last): File ", line 1, in a [0] = 5TypeError: 'tuple' object does not support item assignment3.2 must enter the pit

The worst bug I've ever written after using Python for years is the following code.

> > import threading > def do_something (name): print ('My name is% s.'%name) > th = threading.Thread (target=do_something, args= ('xufive')) > th.start () Exception in thread Thread-1:Traceback (most recent call last): File "C:\ Users\ xufive\ AppData\ Local\ Programs\ Python\ Python37\ lib\ threading.py", line 926 In _ bootstrap_inner self.run () File "C:\ Users\ xufive\ AppData\ Local\ Programs\ Python\ Python37\ lib\ threading.py", line 870, in run self._target (* self._args, * * self._kwargs) TypeError: do_something () takes 1 positional argument but 6 were given

I clearly provided only one parameter, but I was prompted to say that six parameters were given. Why? Originally, when a tuple is initialized, if there is only a single parameter, you must add a comma (,) after the single parameter, otherwise, the initialization result will only return the original parameter.

> > a = (5) > > a5 > type (a) > > b = ('xyz') > type (b) > a, b = (5,), (' xyz',) > a, b ((5,), ('xyz',)) > type (a), type (b) (' tuple' >, 'tuple' >) 3.3 single star unpackaged tuples

When formatting output strings, the C language style is my favorite. When there are multiple% to match, the following is perhaps the most natural way to write.

> args = (95pc99100) > >% s: Chinese% d, math% d, English% d'% ('Tianyuan prodigal son', args [0], args [1], args [2]) 'Tianyuan prodigal son: Chinese 95, math 99, English 100'

Right is right, but not good enough. Full marks should be written like this.

> args = (9599100) > >% s: Chinese% d, math% d, English% d'% ('Tianyuan prodigal son', * args) 'Tianyuan prodigal son: Chinese 95, math 99, English 1003.4 Why use tuples?

Why use tuples when the elements of tuples are immutable? Isn't it more convenient to use lists instead of tuples? It is true that in most cases, lists can be used instead of tuples, but the following example proves that lists cannot replace tuples.

> s = {1 TypeError, (3 line 4) 5)} > s {1, (3 Jing 4 Jing 5),'x'} > s = {1 TypeError Xuan, [3 Jing 4 Jing 5]} Traceback (most recent call last): File ", line 1, in s = {1 pm 4 Jing 5]} TypeError: unhashable type: 'list'

We can add tuples to the collection, but not the list, because the list is unhashable-free. It is not difficult to understand this: list elements can be changed dynamically, so there is no fixed hash value-which conflicts with the uniqueness of the elements required by the collection; while tuple elements are prohibited from updating, and their hash values do not change throughout the life cycle, so they can become elements of the collection.

Obviously, tuples and lists are stored in completely different ways. Because you don't have to worry about updates, tuples have much better speed performance than lists. Giving priority to tuples should be a basic principle followed by Python programmers.

This is the end of the content of "how to use square brackets, curly braces and parentheses in Python". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Internet Technology

Wechat

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

12
Report