如何在列表的一个元素中拆分信息
How do you split information in one element of a list
我不确定我问的是否正确,但我正在尝试从包含多个元素的列表中提取一个元素并拆分信息。
以英尺和英寸为例:
['5-11', '6-7', '6-1']
我怎样才能将这些元素中的 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 {}.
如果列表的元素确实是字符串而不是 int 减法,您只需在 '-'
上的索引 0
处拆分列表项,然后通过简单地解包将其提供给 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)
我不确定我问的是否正确,但我正在尝试从包含多个元素的列表中提取一个元素并拆分信息。
以英尺和英寸为例:
['5-11', '6-7', '6-1']
我怎样才能将这些元素中的 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 {}.
如果列表的元素确实是字符串而不是 int 减法,您只需在 '-'
上的索引 0
处拆分列表项,然后通过简单地解包将其提供给 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)