li = [11,22,33,44,55,66,77,88,99]

result = {}

for row in li:

  if row >66

    if  'key1' not in result:

      result['key1'] = [] 

      result['key1'].append(row)

    else 

      result['key1'].append(row)

  else

    if  'key1' not in result:

      result['key2'] = []  

    result['key2'].append(row)

#因为if内的内容只执行一次,为了避免重复代码

 

 

def func1(lis= [])

  lis.append[1]

  print(lis)

func()

func()

func([])

func()

func()

#如果默认参数是可变数据类型,调用时不传值的话会共享这个数据

 

#返回奇数位

def func(lis):

  return lis[1::2]

 

#判断输入值长度

def func(x):

  return len(x)>5

 

#如果输入大于两位,则返回前两位

def func(lis):

  return lis[:2]        #如果原列表长度小于切片位数,则会返回原列表

 

#统计传入字符串中的各种个数

def func(s):

  dic = {'num':0, 'alpha':0, 'space':0, 'other':0}

  for i in s:

    if i.isdigit():

      dic['num'] += 1

    elif i.isalpha():

      dic['alpha'] += 1

    elif i.isspace():

      dic['space'] += 1

    else

      dic['other'] += 1

  return dic

 

###############################################

调整为下面格式:

list3 = [
{'name':'alex','hobby':'抽烟'},
{'name':'alex','hobby':'喝酒'},
{'name':'alex','hobby':'烫头'},
{'name':'egon','hobby':'喊麦'},
{'name':'alex','hobby':'Massage'},
{'name':'egon','hobby':'街舞'},
]

list4 = []
for item in list3:
for dic in list4:
if item['name'] == dic['name']:
dic['hobby_list'].append(item['hobby'])
break
else:
list4.append({'name':item['name'],'hobby_list':[item['hobby']]})

print(list4)

结果[{'name': 'alex', 'hobby_list': ['抽烟', '喝酒', '烫头', 'Massage']}, {'name': 'egon', 'hobby_list': ['喊麦', '街舞']}]


##########################################################

递归实现列表剥皮

def f(x):
  ret = []
  for b in x:
    if isinstance(b,list):
      for a in f(b):
        ret.append(a)
    else:
      ret.append(b)
  return ret