将列表转换为特定格式 [(123, 123), (345,875)..]
我有以下列表:
l = [12,23,54,67,87,98,15,90,44,81]
我想将它们转换为带有括号的对。所需的输出应如下:
[(12,23),(54,67),(87,98),(15,90),(44,81),(44,81)]
我尝试过的是远的?
print('{}'。格式(''
。我该如何解决?
I have the following list:
l = [12, 23,54, 67, 87,98,15, 90, 44,81]
I would like to convert them into pairs with parenthesis. Desired output should look like the following:
[(12, 23),(54, 67), (87,98),(15, 90), (44,81)]
What I tried so far?
print('{}'.format(' '.join('({},)'.format(i) for i in l)))
This does not print the list as pairs. How do I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用一个范围来设置逐步逐步的增量,而不是中的i
。范围需要3个参数 - 一个起始数,一个结数和((可选的;默认为1))增量。
这样的东西:
tuple_list = [(l [i],l [i+1])在范围内(0,len(l),2)]
Rather than
for i in l
, you'd need to use a range to allow you to set an increment by which to step through. range takes 3 arguments - a starting number, an end number, and (optionally; it defaults to 1) an increment.Something like this:
tuple_list = [(l[i], l[i+1]) for i in range(0, len(l), 2)]