I have a list that consists of this:
[['Esté', 'Double', 'Medium', ' £10 ', '0.5', nan, nan, nan, 254.0, 239.0, 224.0, 717.0],
['Esté', 'Double', 'Medium', ' £10 ', '1.0', nan, nan, nan, 248.0, 224.0, 205.0, 677.0]]
I wish for the first three floats to be merged together like this:
[['Esté', 'Double', 'Medium', ' £10 ', '0.5', nan, nan, nan, 254239224, 717.0],
['Esté', 'Double', 'Medium', ' £10 ', '1.0', nan, nan, nan, 24822205, 677.0]]
I need to leave the final float as its own element. The three floats need to change data type to int (to remove the decimal place) and then they need to be merged together as one element. I am having great trouble as to how I can do this.
e.g.
254.0, 239.0, 224.0 --> 254239224
答案 0 :(得分:1)
为了便于理解,我将这分为三个步骤;你可以将它作为单行推导。
slice = src[-4:-1] # This grabs the three items
big_str = ''.join([str(int(x)) for x in slice])
big_int = int(big_str)
在此之后,只需将原始物品贴在一起:
src = src[:-4] + [big_int] + src[-1]
这会让你感动吗?
答案 1 :(得分:0)
加入这些花车 254.0,239.0,224.0 - > 254239224
for l in list_of_lists:
floats = l[index_of_first_float:index_of_last_float+1]
concat = ''.join([str(int(f)) for f in floats])
...
答案 2 :(得分:0)
您需要遍历输入以获取每个列表。从那里,使用列表切片将n-4到n-1个元素合并,并作为列表的一部分!
由于这些元素是浮点数,并且您希望输出为忽略小数的字符串,因此可以使用lambda迭代each[-4:-1]
中的每个元素,例如。 [254.0, 239.0, 224.0]
,将其转换为int,然后转换为字符串。结果是['254', '239', '224.0']
。要合并它们,请使用str.join()
!然后,将合并的结果插入列表的正确位置!
即,
print [each[:-4]+[''.join(map(lambda x:str(int(x)),each[-4:-1]))]+[each[-1]] for each in r]
答案 3 :(得分:0)
您可以使用map和lambda进行此操作
map(lambda x: x[:-4]+[int(''.join(map(str, (map(int, x[-4:-1])))))]+[x[-1]], list_of_lists)
输出:
[['Esté', 'Double', 'Medium', ' £10 ', '0.5', nan, nan, nan, 254239224, 717.0],['Esté', 'Double', 'Medium', ' £10 ', '1.0', nan, nan, nan, 24822205, 677.0]]