python一些简单操作

1.将列表中的所有元素组合成字符串

a = ["Python", "is", "awesome"]
print(" ",join(a))

2.查找列表中频率最高的值

# most frequent element in a list

a = [1, 2, 3, 1, 2, 3, 2, 2, 4, 5, 1]
print(max(set(a), key = a.count))
# using Counter from collections

from collections import Counter

cnt = Counter(a)
print(cnt.most_common(3))

3.检查两个字符串是不是由相同字母不同顺序组成

from collections import Counter
Counter(str1) == Counter(str2)

4.反转字符串

//reversing string with special case of slice step param.
a = 'abcdefghijklmnopqrstuvwxyz'
print(a[::-1])

//iterating over string contents in reverse efficiently.
for char in reversed(a):
      print(char)
//reversing an integer through type conversion and slicing.
num = 123456789
print(int(str(num)[::-1]))

5.反转列表

"""reverssing list with apecial case of slice step param."""
a = [5, 4, 3, 2, 1]
print(a[::-1])
"""iterating over list contents in reverse efficiently."""
for ele in reversed(a):
      print(ele)

6.转置二维数组

#transponse 2d array [[a,b], [c,d], [e,f]] -> [[a,c,e], [b,d,f]]
original = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*original)
print(list(transposed))

7.链式比较

"""chained comparison with all kind of operators"""
b = 6
print(4 < b < 7)
print(1 == b < 20)
  1. 链式函数调用
"""calling different functions with same arguments based on condition"""
def product(a, b):
      return a * b

def add(a, b):
      return a + b

b = True
print((product if b else add)(5, 7))
  1. 字典get方法
"""returning None or default value, when key is not in dict"""
d = {'a':1, 'b':2}
print(d.get('c',3))
  1. 通过[键]排序字典元素
"""Sort a dictionary by its values with the built-in sorted() function and a 'key' argument."""
d = {'apple':10, 'orange':20, 'banana':5, 'rotten':1}
print(sorted(d.items(), key=lambda x: x[1]))
"""Sort using operator.itemgetter as the sort key instead of a lambda"""
from operator import itemgetter
print(sorted(d.items(), key=itemgetter(1)))

"""Sort dict keys by value"""
print(sorted(d, key=d.get))
"""
[('rotten', 1), ('banana', 5), ('apple', 10), ('orange', 20)]
[('rotten', 1), ('banana', 5), ('apple', 10), ('orange', 20)]
['rotten', 'banana', 'apple', 'orange']
"""
  1. 转换列表为逗号分隔符格式
"""converts list to comma separated string"""
items = ['foo', 'bar', 'xyz']
print(','.join(items))
"""list of numbers to comma separated"""
numbers = [2, 3, 5, 10]
print(','.join(map(str, numbers)))
"""list of mix data"""
data = [2, 'hello', 3, 3.4]
print(','.join(map(str, data))).
"""
foo,bar,xyz
2,3,5,10
2,hello,3,3.4
"""
  1. 合并字典
"""merge dict's"""
d1 = {'a': 1}
d2 = {'b': 2}
print({**d1, **d2})
print(dict(d1.items() | d2.items()))

d1.update(d2)
print(d1)
"""
{'a': 1, 'b': 2}
{'b': 2, 'a': 1} 或 {'a': 1, 'b': 2}
{'a': 1, 'b': 2}
"""
  1. 列表中最小和最大值的索引
"""Find Index of Min/Max Element."""
list = [40, 10, 20, 30]
def minIndex(list):
      return min(range(len(list)), key=list.__getitem__)

def maxIndex(list):
      return max(range(len(list)), key=list.__getitem__)

print(minIndex(list))
print(maxIndex(list))
"""
1
0
"""
  1. 移除列表中的重复元素
"""remove duplicate items from list. note: does not preserver the original list order"""
items = [2, 2, 3, 3, 1]
newitems2 = list(set(items))
print(newitems2)
"""remove dups and keep order"""
from collections import OrderedDict
items = ["foo", "bar", "bar", "foo"]
print(list(OrderedDict.fromkeys(items).keys()))
"""
[1, 2, 3]
['foo', 'bar']
"""
Live what we love, do what we do, follow the heart, and do not hesitate.
原文地址:https://www.cnblogs.com/failan/p/13977760.html