欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

一句话Python

程序员文章站 2022-07-12 15:09:42
...

一句话Python即在一条语句中添加多个条件,生成满足要求的数据.

1 生成list

通过遍历字符串,生成list.

1.0 strip清洗字符串首尾空格和换行符

  • Demo
e = " 我是天蓝蓝 "
# 
default_strip = [element for element in e.strip()] 
print("Type of strip: {}".format(type(e.strip())))
print("Default strip: {}".format(default_strip))
  • Result
Type of strip: <class 'str'>
Default strip: ['我', '是', '天', '蓝', '蓝']
  • Analysis
    (1) 通过strip去除字符串的首尾的空格;
    (2) 去除空格后,遍历字符串;

1.2 直接遍历字符串

  • Demo
e = " 我是天蓝蓝 "
default_strip = [element for element in e] 
print("Type of strip: {}".format(type(e)))
print("Default strip: {}".format(default_strip))
  • Result
Type of strip: <class 'str'>
Default strip: [' ', '我', '是', '天', '蓝', '蓝', ' ']
  • Analysis
    直接遍历字符串所有元素,未对字符串进行任何处理;

1.3 去除字符串中的空格

  • Demo
st = "我是你的宝贝 \n"
li_with_space = [s for s in st]
li_without_space = [s for s in st if s != " "]
print("list with space: {}".format(li_with_space))
print("list without space: {}".format(li_without_space))
  • Result
list: ['我', '是', '你', '的', '宝', '贝', ' ', '\n']
list: ['我', '是', '你', '的', '宝', '贝', '\n']

2 获取元素编号

  • Demo
train_buckets_scale = [0.435, 0.78, 0.96, 1.0]
bucket = [i for i in range(len(train_buckets_scale))]
bucket_id_min = min([i for i in range(len(train_buckets_scale)) if train_buckets_scale[i] > 0.8])
bucket_id_max = max([i for i in range(len(train_buckets_scale)) if train_buckets_scale[i] > 0.8])
if train_buckets_scale[i] > 0.3]
print("bucket id: {}".format(bucket))
print("bucket id min: {}".format(bucket_id_min))
print("bucket id max: {}".format(bucket_id_max))
  • Result
bucket id: [0, 1, 2, 3]
bucket id min: 2
bucket id max: 3
  • Analysis
    (1) 语句中加入条件,min获取满足条件的最小值,max获取满足条件的最大值;
    (2) min(2, 3)=2,max(0, 1, 2, 3)=3

3 list转str

  • Demo
l = ['我', '是', '你', '的', '宝贝', '\n']
print("type of source data: {}".format(type(l)))
string = "".join(l)
print("type of result: {}".format(type(string)))
print("string: {}".format(string))
  • Result
type of source data: <class 'list'>
type of result: <class 'str'>
string: 我是你的宝贝
  • Analysis
    (1) 直接通过join即可将list转为str