在Python 2.7.6中选择列表中的元素

时间:2014-08-05 05:56:06

标签: python list

在Python 2.7.6中,列表如下。以什么方式我可以拿起物品开始于" 4"长度为4,即低于4646和4648?

aaa = [2013, 2014, 2002, 4646, 4648, 20, 456, 5623, 'abc']

我只能通过以下方式选择4个长度:

results = []

for number in aaa:
  if len(str(number)) == 4:
      results.append(number)

print results

感谢。


都是很棒的答案。但我是新手,所以选择最简单的。 :)

6 个答案:

答案 0 :(得分:5)

使用整数:

result = [x for x in aaa if 4000 <= x < 5000]

使用字符串:

result = [x for x in aaa if len(str(x)) == 4 and str(x).startswith('4')]

答案 1 :(得分:1)

我想知道这就是你想要的

results = []

for number in aaa:
  if str(number)[0] == '4' and len(str(number)) == 4:
      results.append(number)

print results

答案 2 :(得分:1)

使用过滤器:

filtered = list(filter(lambda x: len(str(x)) == 4 and str(x)[0] == '4', aaa))

使用列表理解:

filtered = [ x for x in aaa if len(str(x)) == 4 and str(x)[0] == '4' ]

使用生成器表达式:

ge = ( x for x in aaa if len(str(x)) == 4 and str(x)[0] == '4' )
filtered = list(ge)

现已过滤:[4646, 4648]

答案 3 :(得分:1)

只需:

aaa = [2013, 2014, 2002, 4646, 4648, 20, 456, 5623, 'abc']
result = [x for x in aaa if str(x).startswith("4") and len(str(x))==4]

答案 4 :(得分:1)

希望这会取得你想要的结果。

aaa = [2013, 2014, 2002, 4646, 4648, 20, 456, 5623, 'abc']
results = []
for number in aaa:
    if len(str(number)) == 4 and str(number).split()[0][0] == '4':
        results.append(number)
print results 

Output: [4646, 4648]

答案 5 :(得分:1)

尝试以下代码行:

aaa = [2013, 2014, 2002, 4646, 4648, 20, 456, 5623, 'abc']

results = []

for number in aaa:
  if len(str(number)) == 4 and str(number)[0] == '4':
  results.append(number)

print results

我只更改了你的if语句,如:

  

如果len(str(number))== 4和str(number)[0] =='4':