我不确定我是否问对了,但是我试图在一个包含几个元素的列表中提取一个元素,然后将信息分开。
例如,以英尺和英寸为例:
['5-11', '6-7', '6-1']
我怎么能把其中的一个元素分解成这样的东西:
"the person is 5 feet 11 inches tall." #example
这就像将5和11从一个元素中分离出来一样。
分裂元素是可能的吗?这样我就可以把5和11分开了吗?
到目前为止,我的代码:
def splitter(list1)
print(list[1])
return "The guy is {} feet {} inches tall.".format(list[1], list[1]) #I am aware taking the same index of list will give me 5-11 for both {}.
发布于 2016-12-10 00:27:32
如果列表中的元素确实是字符串而不是int减法,那么只需在'-'
上的索引处拆分列表项,然后通过简单的解压缩将其提供给format
:
def splitter(list1):
return "The guy is {} feet {} inches tall.".format(*list1[0].split('-'))
或者,为了更清楚地知道你在做什么:
def splitter(list1):
feet, inches = list1[0].split('-')
return "The guy is {} feet {} inches tall.".format(feet, inches)
https://stackoverflow.com/questions/41070791
复制相似问题