Python assigns values ​​​​to multiple variables at the same time

高洛峰
Release: 2016-10-19 15:11:22
Original
3773 people have browsed it

Assign multiple values ​​at the same time

Here’s a cool programming shortcut: In Python, you can use tuples to assign multiple values ​​at once

.

>>> v = ('a', 2, True)

>>> (x, y, z) = v ①

>>> x

'a'

>>> y

2

>>> z

True

1. v is a tuple of three elements, and (x, y, z) is a tuple of three variables. Assigning one to the other will assign each value in v to each variable in order. This feature has several uses. Suppose you need to assign a name to a specific range of

values. You can use the built-in range() function for multi-variable assignment to quickly perform continuous variable assignments.

>>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,

SATURDAY, SUNDAY) = range(7) ①

>>> MONDAY                                                   

0

>>> TUESDAY

1

>>> SUNDAY

6

1. The built-in range() function constructs an integer sequence. (Technically, the range() function returns neither a list nor a tuple, but an iterator, but you'll learn the difference later.) MONDAY, TUESDAY, WEDNESDAY , THURSDAY, FRIDAY, SATURDAY and SUNDAY are variables defined by you. (This example comes from the calendar module, a short and fun module that prints a calendar, somewhat like the UNIX program cal. The calendar module defines integer constants for the day of the week.

2. Now, each variable has its The value is: MONDAY is 0, TUESDAY is 1, and so on.

You can also use multi-variable assignment to create a function that returns multiple values. The caller can just return a tuple containing all the values. Treat the value as a simple tuple, or

assign it to a different variable

.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!