本文介绍了将逗号分隔的数字分成对的 Pythonic 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将逗号分隔的值分成对:
>>>s = '0,1,2,3,4,5,6,7,8,9'>>>对 = # 一些 Pythonic 的东西>>>对[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]#something pythonic 会是什么样子?
您将如何检测和处理具有奇数组数字的字符串?
解决方案
类似:
zip(t[::2], t[1::2])
完整示例:
>>>s = ','.join(str(i) for i in range(10))>>>秒'0,1,2,3,4,5,6,7,8,9'>>>t = [int(i) for i in s.split(',')]>>>吨[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>>p = zip(t[::2], t[1::2])>>>磷[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]>>>如果项目数是奇数,最后一个元素将被忽略.只包含完整的对.
I'd like to split a comma separated value into pairs:
>>> s = '0,1,2,3,4,5,6,7,8,9'
>>> pairs = # something pythonic
>>> pairs
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
What would # something pythonic look like?
How would you detect and handle a string with an odd set of numbers?
解决方案
Something like:
zip(t[::2], t[1::2])
Full example:
>>> s = ','.join(str(i) for i in range(10))
>>> s
'0,1,2,3,4,5,6,7,8,9'
>>> t = [int(i) for i in s.split(',')]
>>> t
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> p = zip(t[::2], t[1::2])
>>> p
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>>>
If the number of items is odd, the last element will be ignored. Only complete pairs will be included.
这篇关于将逗号分隔的数字分成对的 Pythonic 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!