您的位置:首页 > 健康 > 养生 > 免费正规的接单平台代加工_别傻乎乎跑去银行卡销户了_怎样推广自己的app_亚马逊跨境电商

免费正规的接单平台代加工_别傻乎乎跑去银行卡销户了_怎样推广自己的app_亚马逊跨境电商

2025/4/2 5:38:21 来源:https://blog.csdn.net/xiaoyw/article/details/145755086  浏览:    关键词:免费正规的接单平台代加工_别傻乎乎跑去银行卡销户了_怎样推广自己的app_亚马逊跨境电商
免费正规的接单平台代加工_别傻乎乎跑去银行卡销户了_怎样推广自己的app_亚马逊跨境电商

列表(List)是 Python 中最常用的数据结构之一,它是一个有序、可变的集合,可以存储任意类型的元素。以下是列表的定义及常见用法,包括拼接、增加数据、插入数据、删除数据、计算差值、相加、清空等操作,与字典和pandas结合使用场景比较多。

1. python列表常用基本方法

操作方法或语法示例
定义列表[]my_list = [1, 2, 3]
列表拼接+extend()list1 + list2list1.extend(list2)
增加数据append()extend()my_list.append(4)
插入数据insert()my_list.insert(1, 1.5)
删除数据remove()pop()delmy_list.remove(3)
计算列表差值集合操作 set(list1) - set(list2)difference = list(set(list1) - set(list2))
列表数据相加减列表推导式或 zip()[x + y for x, y in zip(list1, list2)]
清空列表clear()my_list.clear()
获取列表长度len()len(my_list)
检查元素是否存在inif 3 in my_list:
列表(原地)排序sort()my_list.sort()
列表(新)排序sorted()my_list.sorted()
列表反转reverse()my_list.reverse()

1.1. 删除数据

1.1.1. 使用 remove() 删除指定值

remove() 方法会删除列表中第一个匹配的值。如果值不存在,会抛出 ValueError 异常。

my_list = [1, 2, 3, 4, 3]
my_list.remove(3)  # 删除第一个值为 3 的元素
print(my_list)  # 输出: [1, 2, 4, 3]

1.1.2. 使用 pop() 删除指定索引的元素

pop() 方法根据索引删除元素,并返回被删除的值。如果不指定索引,默认删除最后一个元素。

my_list = [1, 2, 3, 4]
removed_value = my_list.pop(2)  # 删除索引为 2 的元素
print(my_list)  # 输出: [1, 2, 4]
print(removed_value)  # 输出: 3

1.1.3. 使用 del 删除指定索引或切片

my_list = [1, 2, 3, 4, 5]
del my_list[1]  # 删除索引为 1 的元素
print(my_list)  # 输出: [1, 3, 4, 5]del my_list[1:3]  # 删除索引 1 到 2 的元素
print(my_list)  # 输出: [1, 5]

删除切片范围内的元素。

1.1.4. 列表推导式删除数据

在 Python 中,你可以使用列表推导式结合集合操作来从 SoC 列表中提取 EID 不在 units_discharge 中的元素。首先,我们需要将 units_discharge 列表转换为一个集合,以便进行快速的成员资格测试。然后,我们可以使用列表推导式来筛选出符合条件的元素。

下面是具体的实现代码:

SoC = [{'EID': 'CN1', 'SoC': 0.2}, {'EID': 'CN2', 'SoC': 0.6}, {'EID': 'CN3', 'SoC': 0.1}, {'EID': 'CN4', 'SoC': 0.9}]
units_discharge = [{'EID': 'CN4'}, {'EID': 'CN2'}]# 将 units_discharge 转换为一个包含 EID 的集合
eid_set = {item['EID'] for item in units_discharge}# 使用列表推导式筛选 EID 不在 eid_set 中的元素
filtered_SoC = [item for item in SoC if item['EID'] not in eid_set]print(filtered_SoC)

这段代码首先通过集合推导式{item['EID'] for item in units_discharge} 创建了一个包含所有 units_discharge 中 EID 的集合 eid_set。然后,它使用列表推导式[item for item in SoC if item['EID'] not in eid_set]来筛选 SoC 列表中 EID 不在 eid_set 中的元素。

运行这段代码,你将得到以下输出:

[{'EID': 'CN1', 'SoC': 0.2}, {'EID': 'CN3', 'SoC': 0.1}]

这正是我们期望的结果,即 EID 不在 units_discharge 中的 SoC 列表元素。

1.1.5. 使用 filter() 函数

filter() 函数可以根据条件过滤列表中的元素,返回一个迭代器。可以将其转换为列表。

my_list = [1, 2, 3, 4, 3, 5]
new_list = list(filter(lambda x: x != 3, my_list))  # 过滤掉值为 3 的元素
print(new_list)  # 输出: [1, 2, 4, 5]

注意事项:

  • filter() 返回的是一个迭代器,需要转换为列表。
  • 这种方法也不会修改原列表。

1.1.6. 使用 clear() 方法(删除所有元素)

如果需要删除列表中的所有元素(即清空列表),可以使用 clear() 方法。

my_list = [1, 2, 3, 4, 5]
my_list.clear()  # 清空列表
print(my_list)  # 输出: []

1.2. 两组列表数据相加减

1.2.1. 计算两个列表的差值

可以使用集合(set)操作来计算两个列表的差值。

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7]
difference = list(set(list1) - set(list2))  # 计算 list1 有而 list2 没有的元素
print(difference)  # 输出: [1, 2, 3]

1.2.2. 两个列表数据相加

可以使用列表推导式或 zip() 函数对两个列表的元素逐项相加。

1.2.2.1. 使用列表推导式
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = [x + y for x, y in zip(list1, list2)]
print(result)  # 输出: [5, 7, 9]
1.2.2.2. 使用 zip() 函数
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = []
for x, y in zip(list1, list2):result.append(x + y)
print(result)  # 输出: [5, 7, 9]

1.3. 增加数据

可以使用 append() 方法在列表末尾添加单个元素,或使用 extend() 方法添加多个元素。

1.3.1. 使用 append()

my_list = [1, 2, 3]
my_list.append(4)  # 添加单个元素
print(my_list)  # 输出: [1, 2, 3, 4]

1.3.2. 使用 extend()

my_list = [1, 2, 3]
my_list.extend([4, 5])  # 添加多个元素
print(my_list)  # 输出: [1, 2, 3, 4, 5]

1.4. 插入数据

使用 insert() 方法可以在指定位置插入元素。

my_list = [1, 2, 3]
my_list.insert(1, 1.5)  # 在索引 1 处插入 1.5
print(my_list)  # 输出: [1, 1.5, 2, 3]

1.5. 列表拼接

可以使用 + 运算符或 extend() 方法拼接两个列表。

1.5.1. 使用 + 运算符

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)  # 输出: [1, 2, 3, 4, 5, 6]

1.5.2. 使用 extend() 方法

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)  # 将 list2 拼接到 list1
print(list1)  # 输出: [1, 2, 3, 4, 5, 6]

1.6. 清空列表

使用 clear() 方法可以清空列表。

my_list = [1, 2, 3, 4, 5]
my_list.clear()  # 清空列表
print(my_list)  # 输出: []

1.7. 列表排序

1.7.1. 列表sort()排序

my_list = [3, 1, 4, 1, 5, 9]
my_list.sort()  # 升序排序
print(my_list)  # 输出: [1, 1, 3, 4, 5, 9]my_list.sort(reverse=True)  # 降序排序
print(my_list)  # 输出: [9, 5, 4, 3, 1, 1]

使用 sorted() 函数会返回一个新的排序后的列表,原列表不会被修改。

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_list = sorted(my_list)
print(sorted_list)  # 输出: [1, 1, 2, 3, 4, 5, 5, 6, 9]
print(my_list)  # 输出: [3, 1, 4, 1, 5, 9, 2, 6, 5] (原列表未改变)

1.7.2. 自定义排序

可以使用 key 参数来指定排序的依据。例如,按字符串长度排序:

my_list = ['apple', 'banana', 'cherry', 'date']
my_list.sort(key=len)
print(my_list)  # 输出: ['date', 'apple', 'cherry', 'banana']

1.7.3. 复杂对象的排序

如果列表中的元素是复杂对象(如字典),可以使用 key 参数来指定排序的依据。

my_list = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
my_list.sort(key=lambda x: x['age'])
print(my_list)
# 输出: [{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

1.8. 列表反转

my_list = [1, 2, 3, 4, 5]
my_list.reverse()  # 反转列表
print(my_list)  # 输出: [5, 4, 3, 2, 1]

1.9. 获取列表长度

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)  # 输出: 5

1.10. 检查元素是否存在

my_list = [1, 2, 3, 4, 5]
if 3 in my_list:print("3 存在于列表中")

2. 列表转字符串方法

如果你想将列表 ['1', '3', '5'] 转换为字符串 "'1', '3', '5'",可以使用 join() 方法结合字符串格式化来实现。以下是具体代码:

# 原始列表
lst = ['1', '3', '5']# 使用 join() 方法将列表中的元素用 ", " 连接,并在每个元素两侧添加单引号
result = ', '.join(f"'{item}'" for item in lst)# 输出结果
print(result)

输出:

'1', '3', '5'

解释:

  1. f"'{item}'" 是一个格式化字符串,它会将列表中的每个元素 item 包裹在单引号中。
  2. ', '.join(...) 将格式化后的元素用逗号和空格连接起来,形成最终的字符串。

如果你希望输出不带空格,比如 "'1','3','5'",可以这样修改:

result = ','.join(f"'{item}'" for item in lst)

输出:

'1','3','5'

3. 列表中字典数据计算

在 Python 中,如果列表里的数据是字典,并且你想计算某个关键字的合计值,可以使用多种方法,包括列表推导式和 sum 函数结合生成器表达式,或者使用传统的循环。以下是几种方法的示例:

3.1. 使用列表推导式和 sum 函数

# 示例数据
data = [{'name': 'Alice', 'score': 85},{'name': 'Bob', 'score': 90},{'name': 'Charlie', 'score': 78},
]# 计算 'score' 的合计值
total_score = sum([d['score'] for d in data])print(total_score)  # 输出: 253

3.2. 使用生成器表达式和 sum 函数

生成器表达式比列表推导式更节省内存,因为它不会一次性生成整个列表,而是按需生成元素。

# 计算 'score' 的合计值
total_score = sum(d['score'] for d in data)print(total_score)  # 输出: 253

3.3. 使用传统的循环

这种方法比较直观,适合初学者理解。

# 计算 'score' 的合计值
total_score = 0
for d in data:total_score += d['score']print(total_score)  # 输出: 253

总结:

  • 列表推导式:适合用于需要生成列表的场景,但在这种情况下,如果只是为了求和,生成整个列表可能不太高效。
  • 生成器表达式:更高效,因为它不会一次性生成整个列表,而是按需生成元素。
  • 传统循环:简单直观,适合初学者,性能也不错。

在实际应用中,你可以根据具体需求和代码风格选择适合的方法。对于求和这种操作,生成器表达式和传统循环通常是比较好的选择。

4. Pandas数据转列表字典

在Pandas中,你可以使用DataFrame.to_dict()方法将数据表转换为字典。具体来说,你可以根据需要选择不同的orient参数来控制输出的格式。以下是一些常用的orient参数及其对应的输出格式:

  • 默认(dict: 键是列名,值是每列的数据作为字典。
  • list: 键是列名,值是每列的数据作为列表。
    -. series: 键是列名,值是每列的数据作为Series对象。
  • split: 包含三个键:index, columns, data
  • records: 列表中的每个元素是一个字典,字典的键是列名,值是每行的数据。
  • index: 键是索引,值是每行的数据作为字典。

下面是一些示例代码,展示了如何使用这些不同的orient参数:

import pandas as pd# 创建一个示例DataFrame
data = {'name': ['Alice', 'Bob', 'Charlie'],'age': [25, 30, 35],'city': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)# 默认方式(dict)
dict_default = df.to_dict()
print("Default (dict):")
print(dict_default)# list方式
dict_list = df.to_dict(orient='list')
print("\nList:")
print(dict_list)# series方式
dict_series = df.to_dict(orient='series')
print("\nSeries:")
print(dict_series)# split方式
dict_split = df.to_dict(orient='split')
print("\nSplit:")
print(dict_split)# records方式
dict_records = df.to_dict(orient='records')
print("\nRecords:")
print(dict_records)# index方式
dict_index = df.to_dict(orient='index')
print("\nIndex:")
print(dict_index)

运行上述代码后,你会得到以下输出:

Default (dict):
{'name': {0: 'Alice', 1: 'Bob', 2: 'Charlie'}, 'age': {0: 25, 1: 30, 2: 35}, 'city': {0: 'New York', 1: 'Los Angeles', 2: 'Chicago'}}List:
{'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'city': ['New York', 'Los Angeles', 'Chicago']}Series:
{'name': 0    Alice
1      Bob
2    Charlie
Name: name, dtype: object, 'age': 0    25
1    30
2    35
Name: age, dtype: int64, 'city': 0         New York
1    Los Angeles
2        Chicago
Name: city, dtype: object}Split:
{'index': [0, 1, 2], 'columns': ['name', 'age', 'city'], 'data': [['Alice', 25, 'New York'], ['Bob', 30, 'Los Angeles'], ['Charlie', 35, 'Chicago']]}Records:
[{'name': 'Alice', 'age': 25, 'city': 'New York'}, {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}]Index:
{0: {'name': 'Alice', 'age': 25, 'city': 'New York'}, 1: {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}, 2: {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}}

通过选择合适的orient参数,你可以灵活地将DataFrame转换为不同格式的字典。

5. 实践案例参考

5.1. python推导式及列推导式应用实践

python推导式及列推导式应用实践

5.2. python列表差分与集合(set)应用列表去重

python列表差分与集合应用实践

5.3 python编程技巧——list计算

python编程技巧——list计算

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com