I have following code segment to seperate the first element of list and the rest into two variables:
test1 = [['p', '(q ∧ ¬(q))', '¬(p)'], ['p', '(¬(p) ∧ ¬(¬(p)))', '¬(p)']]
test2 = ['p', '(q ∧ ¬(q))', '¬(p)', 'q']
def seperate(data, index=None):
if index == None:
head = data[0]
origin = data[1:]
else:
head = data[index][0]
origin = data[index][1:]
return (head, origin)
print(seperate(test1,0))
print(seperate(test2))
print(seperate(test1,1))
Output:
('p', ['(q ∧ ¬(q))', '¬(p)'])
('p', ['(q ∧ ¬(q))', '¬(p)', 'q'])
('p', ['(¬(p) ∧ ¬(¬(p)))', '¬(p)'])
This works well. My problem is the look and feel of the function, e.g. by the if else statement.
Cause in both if else blocks nearly exactly the same is done. With a little difference the dimension of the two inputs are not identical.
My question is their a way to optimize the code in that way I only have one assigment head = ...
and one assigment origin = ...
CodePudding user response:
Here is a more concise way to get the same behaviour:
def seperate(data, index=None):
list_to_split = data if index is None else data[index]
return (list_to_split[0], list_to_split[1:])
CodePudding user response:
You could boil it down to:
def seperate(data, index=None):
return(data[0], data[1:]) if index == None else (data[index][0], data[index][1:])
CodePudding user response:
The function should do exactly one thing, and not worry about different mutations of the same thing, especially when the caller of the function gets very little advantage from it. For the caller, what's the difference between these?
seperate(test1, 0)
seperate(test1[0])
Basically nothing.
The function shouldn't accept any index
parameter, and the caller should simply make sure to pass in one list and not a nested list of lists.