python两个元组如何合并,将两个列表连接到python中的元组

I want to use the join function in python (not any other function) to merge two lists into nested lists, assuming the lists are of equal length, for example:

list1 = [1, 2, 3]

list2 = ["a", "b", "c"]

I want it to produce a new list like this:

[[1,"a"], [2,"b"], [3,"c"]]

解决方案

I don't think you understand what str.join is for.

str.join is a string method that takes an iterable (usually a list) of strings and returns a new string object that is a concatenation of those strings separated by the string that the method was invoked on.

Below is a demonstration:

>>> strs = ['a', 'b', 'c']

>>> ''.join(strs)

'abc'

>>> '--'.join(strs)

'a--b--c'

>>>

This means that you would not use str.join for what you are trying to do. Instead, you can use zip and a list comprehension:

>>> list1 = [1, 2, 3]

>>> list2 = ["a", "b", "c"]

>>> [list(x) for x in zip(list1, list2)]

[[1, 'a'], [2, 'b'], [3, 'c']]

>>>

Note however that, if you are on Python 2.x, you may want to use itertools.izip instead of zip:

>>> from itertools import izip

>>> list1 = [1, 2, 3]

>>> list2 = ["a", "b", "c"]

>>> [list(x) for x in izip(list1, list2)]

[[1, 'a'], [2, 'b'], [3, 'c']]

>>>

Like the Python 3.x zip, itertools.izip will return an iterator (instead of a list like the Python 2.x zip). This makes it more efficient, especially when dealing with larger lists.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值