I have two arrays initialized like so:
bins = [['1'], ['2'],...['10']]
tasks = ['1:x', '1:y', '2:x', '2:y', '2:z'.... '10:x', '10:y']
I was trying to iterate through [tasks]
and compare the string value before ':' to each element in [bins]
, and if it matches append tasks[i]
to bins[i]
. So I am expecting bins
to be updated like so:
bins = [[1, 1:x, 1:y]...[10, 10:x, 10:y]]
Then I thought it made sense to split off the content before the ':' in [tasks] to compare effectively, so
I split off the contents of [tasks]
before the ':' and created a new array:
splits = ['1', '1', '2', '2', .....'10', '10']
Now in my code I am actually iterating through [splits]
and trying to append tasks[i]
if splits[i]
is in bins[i]
, using the code below:
for i in range(len(splits)):
if (splits[i] in bins[i]) == True:
bins[i].extend(tasks[i])
The problem is the code above does not find any matches (never returns a True
), and thus bins[i]
is not updated.
Am I not iterating through my arrays correctly? Am I not comparing correctly? How can I compare the first element of [bins]
to each element of [splits]
until it does not match and move onto the next element of bins[i]
and repeat?
CodePudding user response:
I believe this is happening because you are comparing different datatypes. Bin
s contains lists of numbers and split
s contains strings.
Looking at you're questions, it seems like you want something like this:
for a in enumerate(bins):
for b in enumerate(splits):
if bins[a][0] == splits[b]
bins[a].extend(tasks[b])
- Calling enumerate is the same as calling range(len(bins))
- Since the ellements in bins are ints, in lists you want the element on index
i
and the first (and only element) in the list (ifi
was 0 that would be bins[0] which is [1] and then [1][0] and 1 is the element on index 0)
CodePudding user response:
This code seems to work for me:
for i in range(len(tasks)):
for j in range(len(bins)):
if int(tasks[i][0]) in bins[j]:
bins[j].append(tasks[i])
print(bins)
CodePudding user response:
You're comparing string against int
>>> '1' in [1]
False
>>> '1' in [str(1)]
True
>>> int('1') in [1]
True
So do the:
int(splits[i])
And it should send true.
Upd. Regarding your correction, though your code should be working, try to make it more pythonic, maybe that will do better.
>>> if ('1' in ['1']) == True:
... True
...
True
>>> if ('1' in ['1']) == False:
... True
...
>>> if '1' in ['1']:
... print("do things")
... do things
if splits[i] in bins[i]:
bins[i].extend(tasks[i])