So I made a Example List looking like this:
dataList = ["tv", "•", "tv", "tv", "•", "tv", "•", "tv", "tv", "•"]
I want to print out the Items that are enclosed by •.
In this example,
tv, tv
tv
tv, tv
I came up with the following code:
num = 0
num2 = 0
index = 0
boolean = True
for index, elem in enumerate(dataList2):
boolean = True
num = index 1,
num = int(num[0])
if elem == "•":
counter = 0
if boolean:
boolean = False
for elem2 in dataList2[num:]:
counter = counter 1,
counter = int(counter[0])
if elem2 == "•":
print("\n")
num2 = counter num,
num2 = int(num2[0])
for el in dataList2[num:num2]:
print(el, end=" ")
I get this output:
tv tv •
tv tv • tv •
tv tv • tv • tv tv •
tv •
tv • tv tv •
tv tv •
As you can see I get the unwanted behaviour that
tv tv • tv •
tv tv • tv • tv tv •
tv • tv tv •
are included in the output. I tried to fix the behaviour with a boolean but that didnt work out. What did I do wrong?
CodePudding user response:
One possible approach would be to find the indices of the special character, and split the list into chunks between the first and last occurrence:
indices = [i for i, v in enumerate(dataList) if v == "•"]
result = [dataList[indices[i - 1] 1:indices[i]] for i in range(1, len(indices))]
For your input, you get
>>> result
[['tv', 'tv'], ['tv'], ['tv', 'tv']]
Now you can print and do other things with that value. For example:
>>> for s in result:
... print(*s, sep=', ')
tv, tv
tv
tv, tv
It's always better to compute intermediate results than just print them if you plan to reuse them for something else.
CodePudding user response:
dataList = ["tv", "•", "tv", "tv", "•", "tv", "•", "tv", "tv", "•"]
searchFor = "•"
allVals = []
isFound = False
oldIdx = -1
for idx, item in enumerate(dataList):
if item == searchFor:
if isFound:
# loop complete
allVals.append(dataList[oldIdx 1 : idx ])
isFound = False
else:
isFound = True
oldIdx = idx
allVals
[['tv', 'tv'], ['tv', 'tv']]
allStrings = [",".join(x) for x in allVals]
allStrings
['tv,tv', 'tv,tv']
CodePudding user response:
Try the below
data = ["tv", "•", "tv", "tv", "•", "tv", "•", "tv", "tv", "•"]
temp = []
counter = 0
for d in data:
if d == "•":
if counter == 1:
print(','.join(temp))
temp = []
counter = 1
else:
counter = 1
else:
if counter != 0:
temp.append(d)
if temp:
print(','.join(temp))
output
tv,tv
tv
tv,tv
CodePudding user response:
Just a slightly shorter version of the iterative solutions
dataList = ["tv", "•", "tv", "tv", "•", "tv", "•", "tv", "tv", "•"]
sub = ['tv']
for i in dataList:
if i == '•':
if sub[0] == '•':
print(*sub[1:], sep=', ')
sub = []
sub = [i]
Output
tv, tv
tv
tv, tv
