Find index of a list where that list is part of a larger listHow do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonAccessing the index in 'for' loops?How do I remove an element from a list by index in Python?How to make a flat list out of list of lists?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?Find current directory and file's directory
Can a stoichiometric mixture of oxygen and methane exist as a liquid at standard pressure and some (low) temperature?
Why does Carol not get rid of the Kree symbol on her suit when she changes its colours?
Why can't the Brexit deadlock in the UK parliament be solved with a plurality vote?
What are some good ways to treat frozen vegetables such that they behave like fresh vegetables when stir frying them?
C++ check if statement can be evaluated constexpr
Short story about a deaf man, who cuts people tongues
Is this toilet slogan correct usage of the English language?
Why is so much work done on numerical verification of the Riemann Hypothesis?
Doesn't the system of the Supreme Court oppose justice?
Did the UK lift the requirement for registering SIM cards?
Why is the "ls" command showing permissions of files in a FAT32 partition?
Creating two special characters
Does the reader need to like the PoV character?
A variation to the phrase "hanging over my shoulders"
Change the color of a single dot in `ddot` symbol
Shouldn’t conservatives embrace universal basic income?
Has any country ever had 2 former presidents in jail simultaneously?
"It doesn't matter" or "it won't matter"?
The Digit Triangles
Does "he squandered his car on drink" sound natural?
How to make money from a browser who sees 5 seconds into the future of any web page?
Taxes on Dividends in a Roth IRA
What fields between the rationals and the reals allow a good notion of 2D distance?
Non-trope happy ending?
Find index of a list where that list is part of a larger list
How do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonAccessing the index in 'for' loops?How do I remove an element from a list by index in Python?How to make a flat list out of list of lists?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?Find current directory and file's directory
I have various complex lists such as
lista = [3,4,[5,[1,2],0]
listb = [[3,4],0,[1,5],2]
I need to find the position of the items in the top list. My output would be item, index for the first list:
0 3
1 2
2 2
3 0
4 1
5 2
So 5,1,2 are in position 3.
In the other list:
0 1
1 2
2 3
3 0
4 0
5 2
The number of sublists can vary and each sublist can have sublists.
In order to simplify, I have searched for any list with a "," and flatted that into 1 sublist.
I could have a list of individual elements and lists but I could not get the indexes. I also tried converting the individual elements into a single item list and appending it but I still cannot get the index of the sublist.
python python-2.7
add a comment |
I have various complex lists such as
lista = [3,4,[5,[1,2],0]
listb = [[3,4],0,[1,5],2]
I need to find the position of the items in the top list. My output would be item, index for the first list:
0 3
1 2
2 2
3 0
4 1
5 2
So 5,1,2 are in position 3.
In the other list:
0 1
1 2
2 3
3 0
4 0
5 2
The number of sublists can vary and each sublist can have sublists.
In order to simplify, I have searched for any list with a "," and flatted that into 1 sublist.
I could have a list of individual elements and lists but I could not get the indexes. I also tried converting the individual elements into a single item list and appending it but I still cannot get the index of the sublist.
python python-2.7
please post your code and tryings
– Maciej S.
Mar 8 at 0:32
Fix yourlista
, it's missing a closing bracket somewhere which makes your desired output ambiguous
– Olivier Melançon
Mar 8 at 12:35
add a comment |
I have various complex lists such as
lista = [3,4,[5,[1,2],0]
listb = [[3,4],0,[1,5],2]
I need to find the position of the items in the top list. My output would be item, index for the first list:
0 3
1 2
2 2
3 0
4 1
5 2
So 5,1,2 are in position 3.
In the other list:
0 1
1 2
2 3
3 0
4 0
5 2
The number of sublists can vary and each sublist can have sublists.
In order to simplify, I have searched for any list with a "," and flatted that into 1 sublist.
I could have a list of individual elements and lists but I could not get the indexes. I also tried converting the individual elements into a single item list and appending it but I still cannot get the index of the sublist.
python python-2.7
I have various complex lists such as
lista = [3,4,[5,[1,2],0]
listb = [[3,4],0,[1,5],2]
I need to find the position of the items in the top list. My output would be item, index for the first list:
0 3
1 2
2 2
3 0
4 1
5 2
So 5,1,2 are in position 3.
In the other list:
0 1
1 2
2 3
3 0
4 0
5 2
The number of sublists can vary and each sublist can have sublists.
In order to simplify, I have searched for any list with a "," and flatted that into 1 sublist.
I could have a list of individual elements and lists but I could not get the indexes. I also tried converting the individual elements into a single item list and appending it but I still cannot get the index of the sublist.
python python-2.7
python python-2.7
edited Mar 8 at 3:38
John Kugelman
246k54406459
246k54406459
asked Mar 8 at 0:02
AmyAmy
61
61
please post your code and tryings
– Maciej S.
Mar 8 at 0:32
Fix yourlista
, it's missing a closing bracket somewhere which makes your desired output ambiguous
– Olivier Melançon
Mar 8 at 12:35
add a comment |
please post your code and tryings
– Maciej S.
Mar 8 at 0:32
Fix yourlista
, it's missing a closing bracket somewhere which makes your desired output ambiguous
– Olivier Melançon
Mar 8 at 12:35
please post your code and tryings
– Maciej S.
Mar 8 at 0:32
please post your code and tryings
– Maciej S.
Mar 8 at 0:32
Fix your
lista
, it's missing a closing bracket somewhere which makes your desired output ambiguous– Olivier Melançon
Mar 8 at 12:35
Fix your
lista
, it's missing a closing bracket somewhere which makes your desired output ambiguous– Olivier Melançon
Mar 8 at 12:35
add a comment |
2 Answers
2
active
oldest
votes
You can use a function that flattens a given list by iterating through the list items and recursively flattens an item if it is a list. Use the enumerate
function to generate list indices and output them as the second item of a tuple:
def flatten(l):
return [(n, i) for i, v in enumerate(l) for n, _ in (flatten(v) if isinstance(v, list) else ((v, 0),))]
so that given:
lista=[3,4,[5,[1,2]],0]
listb=[[3,4],0,[1,5],2]
the following:
print(flatten(lista))
print(flatten(listb))
will output:
[(3, 0), (4, 1), (5, 2), (1, 2), (2, 2), (0, 3)]
[(3, 0), (4, 0), (0, 1), (1, 2), (5, 2), (2, 3)]
or if you prefer the output to be sorted by the item values:
print(sorted(flatten(lista)))
print(sorted(flatten(listb)))
will output:
[(0, 3), (1, 2), (2, 2), (3, 0), (4, 1), (5, 2)]
[(0, 1), (1, 2), (2, 3), (3, 0), (4, 0), (5, 2)]
add a comment |
You could use a function like this:
def find_index(val, lst):
for i, x in enumerate(lst):
if val == x:
return i
elif type(x) is list: # or type(x) not in float, int
try:
find_index(val, x)
# matched without error
return i
except ValueError:
# not in list
pass
# not found
raise ValueError(' is not in the list'.format(val))
This uses the enumerate
function to get items and their indexes from the list. Then it tests each item directly against the required value if possible. If the item is a list, it checks that recursively instead.
Test:
lst = [[3, 4], 0, [1, [5]], 2]
for x in range(6):
print x, find_index(x, lst)
# 0 1
# 1 2
# 2 3
# 3 0
# 4 0
# 5 2
If you want to be able to work with any type of iterable (not just list
s), you could try this more general code, but it's harder to follow:
def find_index(val, values):
try:
# Search list of items
for i, x in enumerate(values):
try:
find_index(val, x) # any error?
return i # succeeded
except ValueError:
pass
except TypeError:
# not a list, just an item
if values == val:
return 0 # found
# not found
raise ValueError(' is not in the list'.format(val))
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55054768%2ffind-index-of-a-list-where-that-list-is-part-of-a-larger-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can use a function that flattens a given list by iterating through the list items and recursively flattens an item if it is a list. Use the enumerate
function to generate list indices and output them as the second item of a tuple:
def flatten(l):
return [(n, i) for i, v in enumerate(l) for n, _ in (flatten(v) if isinstance(v, list) else ((v, 0),))]
so that given:
lista=[3,4,[5,[1,2]],0]
listb=[[3,4],0,[1,5],2]
the following:
print(flatten(lista))
print(flatten(listb))
will output:
[(3, 0), (4, 1), (5, 2), (1, 2), (2, 2), (0, 3)]
[(3, 0), (4, 0), (0, 1), (1, 2), (5, 2), (2, 3)]
or if you prefer the output to be sorted by the item values:
print(sorted(flatten(lista)))
print(sorted(flatten(listb)))
will output:
[(0, 3), (1, 2), (2, 2), (3, 0), (4, 1), (5, 2)]
[(0, 1), (1, 2), (2, 3), (3, 0), (4, 0), (5, 2)]
add a comment |
You can use a function that flattens a given list by iterating through the list items and recursively flattens an item if it is a list. Use the enumerate
function to generate list indices and output them as the second item of a tuple:
def flatten(l):
return [(n, i) for i, v in enumerate(l) for n, _ in (flatten(v) if isinstance(v, list) else ((v, 0),))]
so that given:
lista=[3,4,[5,[1,2]],0]
listb=[[3,4],0,[1,5],2]
the following:
print(flatten(lista))
print(flatten(listb))
will output:
[(3, 0), (4, 1), (5, 2), (1, 2), (2, 2), (0, 3)]
[(3, 0), (4, 0), (0, 1), (1, 2), (5, 2), (2, 3)]
or if you prefer the output to be sorted by the item values:
print(sorted(flatten(lista)))
print(sorted(flatten(listb)))
will output:
[(0, 3), (1, 2), (2, 2), (3, 0), (4, 1), (5, 2)]
[(0, 1), (1, 2), (2, 3), (3, 0), (4, 0), (5, 2)]
add a comment |
You can use a function that flattens a given list by iterating through the list items and recursively flattens an item if it is a list. Use the enumerate
function to generate list indices and output them as the second item of a tuple:
def flatten(l):
return [(n, i) for i, v in enumerate(l) for n, _ in (flatten(v) if isinstance(v, list) else ((v, 0),))]
so that given:
lista=[3,4,[5,[1,2]],0]
listb=[[3,4],0,[1,5],2]
the following:
print(flatten(lista))
print(flatten(listb))
will output:
[(3, 0), (4, 1), (5, 2), (1, 2), (2, 2), (0, 3)]
[(3, 0), (4, 0), (0, 1), (1, 2), (5, 2), (2, 3)]
or if you prefer the output to be sorted by the item values:
print(sorted(flatten(lista)))
print(sorted(flatten(listb)))
will output:
[(0, 3), (1, 2), (2, 2), (3, 0), (4, 1), (5, 2)]
[(0, 1), (1, 2), (2, 3), (3, 0), (4, 0), (5, 2)]
You can use a function that flattens a given list by iterating through the list items and recursively flattens an item if it is a list. Use the enumerate
function to generate list indices and output them as the second item of a tuple:
def flatten(l):
return [(n, i) for i, v in enumerate(l) for n, _ in (flatten(v) if isinstance(v, list) else ((v, 0),))]
so that given:
lista=[3,4,[5,[1,2]],0]
listb=[[3,4],0,[1,5],2]
the following:
print(flatten(lista))
print(flatten(listb))
will output:
[(3, 0), (4, 1), (5, 2), (1, 2), (2, 2), (0, 3)]
[(3, 0), (4, 0), (0, 1), (1, 2), (5, 2), (2, 3)]
or if you prefer the output to be sorted by the item values:
print(sorted(flatten(lista)))
print(sorted(flatten(listb)))
will output:
[(0, 3), (1, 2), (2, 2), (3, 0), (4, 1), (5, 2)]
[(0, 1), (1, 2), (2, 3), (3, 0), (4, 0), (5, 2)]
edited Mar 8 at 1:35
answered Mar 8 at 1:07
blhsingblhsing
39.7k41743
39.7k41743
add a comment |
add a comment |
You could use a function like this:
def find_index(val, lst):
for i, x in enumerate(lst):
if val == x:
return i
elif type(x) is list: # or type(x) not in float, int
try:
find_index(val, x)
# matched without error
return i
except ValueError:
# not in list
pass
# not found
raise ValueError(' is not in the list'.format(val))
This uses the enumerate
function to get items and their indexes from the list. Then it tests each item directly against the required value if possible. If the item is a list, it checks that recursively instead.
Test:
lst = [[3, 4], 0, [1, [5]], 2]
for x in range(6):
print x, find_index(x, lst)
# 0 1
# 1 2
# 2 3
# 3 0
# 4 0
# 5 2
If you want to be able to work with any type of iterable (not just list
s), you could try this more general code, but it's harder to follow:
def find_index(val, values):
try:
# Search list of items
for i, x in enumerate(values):
try:
find_index(val, x) # any error?
return i # succeeded
except ValueError:
pass
except TypeError:
# not a list, just an item
if values == val:
return 0 # found
# not found
raise ValueError(' is not in the list'.format(val))
add a comment |
You could use a function like this:
def find_index(val, lst):
for i, x in enumerate(lst):
if val == x:
return i
elif type(x) is list: # or type(x) not in float, int
try:
find_index(val, x)
# matched without error
return i
except ValueError:
# not in list
pass
# not found
raise ValueError(' is not in the list'.format(val))
This uses the enumerate
function to get items and their indexes from the list. Then it tests each item directly against the required value if possible. If the item is a list, it checks that recursively instead.
Test:
lst = [[3, 4], 0, [1, [5]], 2]
for x in range(6):
print x, find_index(x, lst)
# 0 1
# 1 2
# 2 3
# 3 0
# 4 0
# 5 2
If you want to be able to work with any type of iterable (not just list
s), you could try this more general code, but it's harder to follow:
def find_index(val, values):
try:
# Search list of items
for i, x in enumerate(values):
try:
find_index(val, x) # any error?
return i # succeeded
except ValueError:
pass
except TypeError:
# not a list, just an item
if values == val:
return 0 # found
# not found
raise ValueError(' is not in the list'.format(val))
add a comment |
You could use a function like this:
def find_index(val, lst):
for i, x in enumerate(lst):
if val == x:
return i
elif type(x) is list: # or type(x) not in float, int
try:
find_index(val, x)
# matched without error
return i
except ValueError:
# not in list
pass
# not found
raise ValueError(' is not in the list'.format(val))
This uses the enumerate
function to get items and their indexes from the list. Then it tests each item directly against the required value if possible. If the item is a list, it checks that recursively instead.
Test:
lst = [[3, 4], 0, [1, [5]], 2]
for x in range(6):
print x, find_index(x, lst)
# 0 1
# 1 2
# 2 3
# 3 0
# 4 0
# 5 2
If you want to be able to work with any type of iterable (not just list
s), you could try this more general code, but it's harder to follow:
def find_index(val, values):
try:
# Search list of items
for i, x in enumerate(values):
try:
find_index(val, x) # any error?
return i # succeeded
except ValueError:
pass
except TypeError:
# not a list, just an item
if values == val:
return 0 # found
# not found
raise ValueError(' is not in the list'.format(val))
You could use a function like this:
def find_index(val, lst):
for i, x in enumerate(lst):
if val == x:
return i
elif type(x) is list: # or type(x) not in float, int
try:
find_index(val, x)
# matched without error
return i
except ValueError:
# not in list
pass
# not found
raise ValueError(' is not in the list'.format(val))
This uses the enumerate
function to get items and their indexes from the list. Then it tests each item directly against the required value if possible. If the item is a list, it checks that recursively instead.
Test:
lst = [[3, 4], 0, [1, [5]], 2]
for x in range(6):
print x, find_index(x, lst)
# 0 1
# 1 2
# 2 3
# 3 0
# 4 0
# 5 2
If you want to be able to work with any type of iterable (not just list
s), you could try this more general code, but it's harder to follow:
def find_index(val, values):
try:
# Search list of items
for i, x in enumerate(values):
try:
find_index(val, x) # any error?
return i # succeeded
except ValueError:
pass
except TypeError:
# not a list, just an item
if values == val:
return 0 # found
# not found
raise ValueError(' is not in the list'.format(val))
edited Mar 8 at 3:29
answered Mar 8 at 1:20
Matthias FrippMatthias Fripp
7,22021628
7,22021628
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55054768%2ffind-index-of-a-list-where-that-list-is-part-of-a-larger-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
please post your code and tryings
– Maciej S.
Mar 8 at 0:32
Fix your
lista
, it's missing a closing bracket somewhere which makes your desired output ambiguous– Olivier Melançon
Mar 8 at 12:35