Python的特殊语法

最后发布时间:2023-03-20 09:15:02 浏览量:

zip()

The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.

languages = ['Java', 'Python', 'JavaScript']
versions = [14, 3, 6]

result = zip(languages, versions)
print(list(result))
print(dict(result))

lambda

# lambda that accepts one argument
greet_user = lambda name : print('Hey there,', name)

# lambda call
greet_user('Delilah')

sorted

mylist = [(3, 5, 8), (6, 2, 8), (2, 9, 4), (6, 8, 5)]
sorted(mylist, key=lambda x: x[1])

Recursion

def factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""
    print(x)
    if x == 1:
        return 1
    else:
        return (x * factorial(x-1))

factorial(3)
3
2
1
dict1 = {'abundance':60,
         'name':'c1',
         'child':[
                {
                'abundance':5,
                'name':'cc1',
                'child':
                    [
                        {
                        'abundance':2,
                        'name':'ccc1',
                        'child':[]
                        },
                        {
                        'abundance':2,
                        'name':'ccc1',
                        'child':[]
                        }
                    ]
                },
                {
                'name':'cc1',
                'abundance':6,
                'child':[]
                }
            ]
        }

def compute_abundance(d):
    sum_ab = sum([compute_abundance(c) for c in d['child']])
    print(d['name'],sum_ab)
    return d['abundance']

compute_abundance(dict1)
ccc1 0
ccc1 0
cc1 4
cc1 0
c1 11
60