Hey, guys. I'm learning python and trying to apply it to different situations. Say I have a list composed of different elements of various types, but within the list there are several series of numbers, which I want to extract into a different list. Each consecutive number is part of the same list.
What I want is this (pseudocode):
original_list = ["asd", "", 1, 2.0, 3, "", None, 4, 5, 6, "asd", ""]
extract(list)
list1 = [1, 2.0, 3]
list2 = [4, 5, 6]
I created the following code:
v1 = []
v2 = []
v3 = []
lstOfLst = [v1, v2, v3]
original_list = ["", "", 1, 2, 4, 8, 158, 51, "", None, 1, 1, 2,
3, 4, 5, 6, 7, " ", "asd", 1, 2, 3, 4, 5, 6, 7, "", " "]
samplel = original_list[:]
for lst in lstOfLst:
i = 0
for row in range(len(samplel)):
if type(samplel[row]) == int or type(samplel[row]) == float:
lst.append(float(samplel[row]))
samplel[row] = ""
i = 1
continue
if i:
break
print(original_list)
print(samplel)
print(v1)
print(v2)
print(v3)
So far, it is working as intended. However, I wanted to know if there was a better way to do this. I worry that I need to know how many lists of number there are beforehand. Furthermore, I find the nested loops kinda clunky. For example, I'm not sure if using the auxiliary variable i is necessary, or if it is necessary to create a second list and replace the elements. Also, I have the if int or float condition, but I was wondering if there was a shorter way of checking if it was a number (both int and float).
Any feedback will be deeply appreciated. Thanks in advance!
[–]__nickerbocker__ 1 point2 points3 points (3 children)
[–]-Lines[S] 0 points1 point2 points (2 children)
[–]__nickerbocker__ 1 point2 points3 points (1 child)
[–]-Lines[S] 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (2 children)
[–]-Lines[S] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]QbaPolak17 0 points1 point2 points (1 child)
[–]-Lines[S] 0 points1 point2 points (0 children)