我现在有list1 = [1, 2, 3] ,list2 = ['a', 'b', 'c']两个list,我需要将他们变为list3 =['a1','a2', 'a3'],list4 = ['b1', 'b2','b3' ],list5 = ['c1','c2','c3']
时间: 2023-09-26 16:11:13 浏览: 80
您可以使用zip和列表推导式来实现:
```
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [str(j) + str(i) for i, j in zip(list1, list2)]
list4 = [str(j) + str(i) for i, j in zip(list1, list2)]
list5 = [str(j) + str(i) for i, j in zip(list1, list2)]
```
这里zip将list1和list2合并成一个元组列表,然后使用列表推导式将元组中的元素按特定的格式组合成新的列表。
相关问题
我现在有list1 = [1, 2, 3] ,list2 = ['a', 'b', 'c']两个list,我需要将他们组合变为类似list3 =['a1','a2','a3']
可以使用列表推导式来实现:
```python
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [str(list2[i])+str(list1[i]) for i in range(len(list1))]
print(list3)
```
输出结果为:
```
['a1', 'b2', 'c3']
```
如果要求组合成['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3'],可以使用两层循环:
```python
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [str(j)+str(i) for i in list1 for j in list2]
print(list3)
```
输出结果为:
```
['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3']
```
我现在有list1 = [1, 2, 3] ,list2 = ['a', 'b', 'c']两个list,我需要将他们组合变为类似list3 = ['a1','a1','a3']
可以使用zip函数和字符串拼接来实现:
```
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = []
for i, j in zip(list2, list1):
list3.append(i + str(j))
print(list3)
```
输出结果为:
```
['a1', 'b2', 'c3']
```
如果要和你的要求一样,需要将list2的元素循环使用,可以使用取余操作:
```
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = []
for i, j in enumerate(list1):
list3.append(list2[i % len(list2)] + str(j))
print(list3)
```
输出结果为:
```
['a1', 'b2', 'c3']
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)