如何删除由(。)分隔并需要联接列表中其他元素的第一个和最后一个元素的第一个和最后一个值

时间:2019-01-25 09:39:15

标签: python list split

我有一个像这样的python列表

['6403687.6403773','6404555.6404614','6413270.6413335']

在这种情况下,我需要删除第一个元素的第一个值(6403687)和最后一个元素的最后一个值(6413335),并需要像这样[[6403773.6404555','6404614.6413270'])加入另一个元素。有几个带有n个值的列表。我不怎么做。如果有人请帮助我。

list = ['6403687.6403773','6404555.6404614','6413270.6413335']

删除第一个和最后一个值后,我需要一个这样的列表

list1 = ['6403773.6404555','6404614.6413270']

4 个答案:

答案 0 :(得分:1)

嗯,做到这一点的一种方法是:

from itertools import islice

lst = ['6403687.6403773','6404555.6404614','6413270.6413335']

# split at ".", flatten and remove both ends (slice)
flat = [num for pair in lst for num in pair.split('.')][1:-1]

# pair the entries in 2s and join them
res = ['.'.join(islice(flat, 2)) for _ in range(len(flat)//2) ]

产生:

print(res)  # -> ['6403773.6404555', '6403773.6404555']

或者,如果您不喜欢islice的最后一步(我也不是忠实拥护者),则可以使用grouper itertool recipe:< / p>

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

然后改为

res = ['.'.join(group) for group in grouper(flat, 2)]

当然会有相同的结果。

答案 1 :(得分:1)

此方法将逐步进行操作,并且也适用于列表或任意长度:

number_strings = ['6403687.6403773','6404555.6404614','6413270.6413335']

# remove first part of element
number_strings[0] = number_strings[0].split('.')[1]

# remove last part of last element
number_strings[-1] = number_strings[-1].split('.')[0]

# remove points
number_strings_rearranged = []
for element in number_strings:
    for part_string in element.split('.'):
        number_strings_rearranged.append(part_string)

# restructure with points
number_strings = [number_strings_rearranged[i]+'.'+number_strings_rearranged[i+1] for i in range(0, len(number_strings_rearranged)-1, 2)]

print(number_strings)

输出:

['6403773.6404555', '6404614.6413270']

答案 2 :(得分:0)

假设您的列表始终为3,因为您没有给出关于动态列表的任何信息:

startList = ['6403687.6403773','6404555.6404614','6413270.6413335']
newList = []
newList.append(startList[0].split('.')[1] + '.' + startList[1].split('.')[0])
# split first value and take second half and concat with the middle value's first half
newList.append(startList[1].split('.')[1] + '.' + startList[2].split('.')[0])
# split last value and take first half and concat with the middle value's second half

输出:

['6403773.6404555','6404614.6413270']

答案 3 :(得分:0)

尽管很多人回答了这个问题,但我想通过使用一个简单的for循环为长列表提出一种不同而又简单的方法。

aa = ['6403687.6403773','6404555.6404614','6413270.6413335']
pr, bb ="", []
for v in aa:
    l, r = v.split(".")
    bb.append(f"{pr}.{l}")
    pr = r
print (bb[1:])

输出:

#Result: ['6403773.6404555', '6404614.6413270']

我希望这会有所帮助:)