本文介绍了在列表中搜索商品,并在python中返回x个周围商品的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在列表中搜索值(x)的出现,并返回该值以及索引中x上下的值(例如2).值x可能会多次出现在列表中.
I want to search a list for the occurence of a value (x) and return that value and a number, say 2, of the values above and below x in the index. Value x might appear in the list multiple time.
输入
in = ['a','b','c','d','x','e','f','g','h','i','x','j','k','l']
输出
out = ['c','d','x','e','f','h','i','x','j','k']
感谢您的帮助或建议
推荐答案
In [8]: lis = ['a','b','c','d','x','e','f','g','h','i','x','j','k','l']
#create a new list containing all the index positions of 'x'
In [9]: ind=[i for i,x in enumerate(lis) if x=='x']
In [10]: out=[]
# loop over ind list, and for every index i:
# here lis[i-2:i] are the elements left to the 'x' and similarly lis[i:i+3]
# are the ones to its right.
# which is simply lis[i-2:i+3] as suggested by @volatility
In [11]: for i in ind:
out.extend(lis[i-2:i+3])
....:
In [12]: out
Out[12]: ['c', 'd', 'x', 'e', 'f', 'h', 'i', 'x', 'j', 'k']
使用 itertools.chain()
的单线:
In [19]: from itertools import *
In [20]: list(chain(*[lis[i-2:i+3] for i in ind]))
Out[20]: ['c', 'd', 'x', 'e', 'f', 'h', 'i', 'x', 'j', 'k']
这篇关于在列表中搜索商品,并在python中返回x个周围商品的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!