문제

Why does the following code throw a SyntaxError for *phones in Python 2.7.3?

contact = ('name', 'email', 'phone1', 'phone2')
name, email, *phones = contact

Was this introduced in Python 3 and not backported? How can I get this to work in Python 2? That is, if there isn't some trivial way to fix things here.

도움이 되었습니까?

해결책

Yup, the extended unpacking syntax (using * to take the rest) is Python 3.x only. The closest you can get in Python 2.x is explicitly slicing the parts you want from the remainder:

contact = ('name', 'email', 'phone1', 'phone2')
(name, email), phones = contact[:2], contact[2:]

If you needed it to work on arbitrary iterables, then you can use something like:

from itertools import islice
i = iter(contact)
(name, email), phone = tuple(islice(i, 2)), list(i)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top