个性化阅读
专注于IT技术分析

Python按符号分组连续元素

本文概述

根据符号给出一组连续元素的列表。

输入:test_list = [5, -3, 2, 4, 6, -2, -1, -7, -9, 2, 3]
输出:[[5], [-3], [2, 4, 6 ], [-2, -1, -7, -9], [2, 3]]
说明:
符号更改时插入新列表的元素。
输入:test_list = [-2, 3, 4, 5, 6, -3]
输出:[[-2], [3、4、5、6], [-3]]
说明:将元素插入到新列表中标志变化。

方法1:使用循环

在这种情况下, 每当符号(正或负)发生变化时, 都会启动一个新列表, 否则将元素添加到与初始化类似的列表中。

Python3

# Python3 code to demonstrate working of 
# Group Consecutive elements by Sign
# Using loop
  
# initializing list
test_list = [ 5 , - 3 , 2 , 4 , 6 , - 2 , - 1 , - 7 , - 9 , 2 , 3 , 10 , - 3 , - 5 , 3 ]
  
# printing original list
print ( "The original list is : " + str (test_list))
  
res = [[]]
for (idx, ele) in enumerate (test_list):
      
     # checking for similar signs by XOR
     if ele ^ test_list[idx - 1 ] <0 :
         res.append([ele])
     else :
         res[ - 1 ].append(ele)
  
# printing result 
print ( "Elements after sign grouping : " + str (res))

输出如下:

原始列表为:[5, -3、2、4、6, -2, -1, -7, -9、2、3、10, -3, -5、3]符号分组后的元素:[[ 5], [-3], [2、4、6], [-2, -1, -7, -9], [2、3、10], [-3, -5], [3]]

方法2:使用groupby()+列表理解

在此, 我们使用groupby()执行分组任务, 并使用列表推导来执行遍历列表的任务。使用lambda函数注入符号的条件。

Python3

# Python3 code to demonstrate working of
# Group Consecutive elements by Sign
# Using groupby() + list comprehension
import itertools
  
# initializing list
test_list = [ - 2 , 3 , 4 , 5 , 6 , - 3 ]
  
# printing original list
print ( "The original list is : " + str (test_list))
  
# grouped using groupby()
res = [ list (ele) for idx, ele in itertools.groupby(test_list, lambda a: a> 0 )]
  
# printing result
print ( "Elements after sign grouping : " + str (res))

输出如下:

原始列表为:[-2、3、4、5、6, -3]
符号分组后的元素:[[-2], [3、4、5、6], [-3]]

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python按符号分组连续元素

评论 抢沙发

评论前必须登录!