How to Extract List from List of Lists When Any One Element Match With Another List'S Element

How to extract list from list of lists when any one element match with another list's element?

I modified your variable name from list to lists because while list is not a reserved keyword, you'd be overwriting the keyword for the list data structure.

lists = [['laravel', 1.0, 54],
['laravel', 1.0, 3615],
['php', 1.0, 1405],
['php', 1.0, 5175],
['php', 1.0, 5176],
['php', 1.0, 54],
['php', 1.0, 5252],
['php', 1.0, 5279],
['python', 1.0, 54],
['laravel', 0.8333333333333334, 54],
['python',0.8333333333333334, 3615]]

skills = {}

for l in lists:
skill, _, id = l
if id in skills:
skills[id].append(skill)
else:
skills[id] = [skill]

output = []
for k in skills.keys():
output.append({
"id": k,
"No_matched_skills": len(skills[k]),
"skills": ",".join(skills[k])
})

print(output)

Let's look at this line by line:

skills = {}

Create a new dictionary so that for each unique ID in the lists variable, we can store a list of skills.

for l in lists:
skill, _, id = l
if id in skills:
skills[id].append(skill)
else:
skills[id] = [skill]

Not sure what that middle variable is so I used _ as its variable name. Change as needed.

I'm using the line skill, _, id = l to unpack the list l into those variables.

If I find the current id in the skills dictionary, I just go ahead and use list.append() to add it to the existing list. Otherwise, I create new list in place with the current skill.

output = []
for k in skills.keys():
output.append({
"id": k,
"No_matched_skills": len(skills[k]),
"skills": ",".join(skills[k])
})

For each key in the skills dictionary, I append a dictionary to the output list. The id is simply the key, No_matched_skills is the size of the list for that key, and I use ",".join(skills[k]) to take that list and save it as a comma-separated string.

Python Extracting items from a sublist if they match an item in another list's sublist

Here is one way of doing that by building a dict to allow easier lookup to the lists to add to:

Code:

lookup = {x[0]: x for x in listA}
for sublist in listB:
lookup.get(sublist[0], []).extend(sublist[1:])

Test Code:

listA = [['x', 'apple', 'orange'], ['y', 'cat', 'dog'], ['z', 'house', 'home']]
listB = [['z', 7, 8, 9], ['x', 1, 2, 3], ['y', 4, 5, 6]]

lookup = {x[0]: x for x in listA}
for sublist in listB:
lookup.get(sublist[0], []).extend(sublist[1:])

print(listA)

Results:

[
['x', 'apple', 'orange', 1, 2, 3],
['y', 'cat', 'dog', 4, 5, 6],
['z', 'house', 'home', 7, 8, 9]
]

R: loop over list of lists to retrieve headers of sublists that contain a hit

There are multiple ways to get the output.

1) An option is to loop over the 'listoflists', subset the vector based on the 'wanted' values, stack it to a two column data.frame and split into a list again by 'values'

with(stack(lapply(listoflists, function(x) 
x[x %in% wanted])), split(as.character(ind), values))
#$apple
#[1] "listA"

#$banana
#[1] "listA" "listB"

#$fig
#[1] "listB" "listC"

2) or we can stack first to a two column 'data.frame', then subset the rows, and split

with(subset(stack(listoflists), values %in% wanted), 
split(as.character(ind), values))
#$apple
#[1] "listA"

#$banana
#[1] "listA" "listB"

#$fig
#[1] "listB" "listC"

3)) Or another option is to loop over the 'wanted' and get the names of the 'listoflists' based on a match

setNames(lapply(wanted, function(x) 
names(which(sapply(listoflists, function(y) x %in% y)))), wanted)
#$apple
#[1] "listA"

#$banana
#[1] "listA" "listB"

#$fig
#[1] "listB" "listC"

How to Remove elements from one List based another list's element and condition?

You can remove the elements like this:

list1.RemoveAll(item => list2.Any(item2 => item.Key == item2.Key))

Findall items in one list matching items in another list's VB.Net

I added a custom constructor to the SelectUsersGrid to make it a bit easier to create New instances to add to the allUserList.

I got rid of the SearListItem class. It seemed sort of silly since it was a class with just one property of a built in type. Changed the searchList to List(Of Integer).

I displayed the allUserList with an interpolated string which became available to vb.net in Visual Studio 2015. In older versions you can use String.Format.

Then comes the line provided by @Jimi in comments. I changed it just a bit since searchList is now a List(Of Integer).

The results is a List(Of SelectUsersGrid). You can see this by holding your cursor over results in the code window. I loop through this list to show the contents of the list.

This is showing Form.Load since I am in a WinForms app. The code will be just as happy in Sub Main.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim allUserList As New List(Of SelectUsersGrid)
allUserList.Add(New SelectUsersGrid(0, "test1"))
allUserList.Add(New SelectUsersGrid(1, "test2"))
allUserList.Add(New SelectUsersGrid(1, "test3"))
allUserList.Add(New SelectUsersGrid(2, "test4"))
allUserList.Add(New SelectUsersGrid(3, "test5"))
allUserList.Add(New SelectUsersGrid(0, "test6"))
allUserList.Add(New SelectUsersGrid(1, "test7"))
allUserList.Add(New SelectUsersGrid(2, "test8"))

Dim searchList As New List(Of Integer)
searchList.Add(0)
searchList.Add(1)

Console.WriteLine("All User List")
For Each item As SelectUsersGrid In allUserList
Console.WriteLine($"User Status {item.UserStatus}, First Name {item.FirstName}")
Next
Dim results = allUserList.Where(Function(usr) searchList.Any(Function(st) st = usr.UserStatus)).ToList()
Console.WriteLine("Output list")
For Each item In results
Console.WriteLine($"User Status {item.UserStatus}, Name {item.FirstName}")
Next
Console.ReadLine()
End Sub

The following class uses auto-implemented properties. You can read about this feature at https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/auto-implemented-properties

Public Class SelectUsersGrid
Public Property UserStatus As Integer
Public Property FirstName As String
Public Sub New(Stat As Integer, Name As String)
UserStatus = Stat
FirstName = Name
End Sub
End Class

How to find list intersection?

If order is not important and you don't need to worry about duplicates then you can use set intersection:

>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]

Using a list's assigned name from a character string in a vector

We can pass the vector list_vec to mget, which returns a nested list. We use lapply to extract ([[) the data element and use unlist to convert this nested list to a list.

unlist(lapply(mget(list_vec), `[[`, "data"), recursive = FALSE)

Result

#$my_list1
#[1] "a" "b" "c"

#$my_list2
#[1] "x" "y" "z"

Take the content of a list and append it to another list

You probably want

list2.extend(list1)

instead of

list2.append(list1)

Here's the difference:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = [7, 8, 9]
>>> b.append(a)
>>> b
[4, 5, 6, [1, 2, 3]]
>>> c.extend(a)
>>> c
[7, 8, 9, 1, 2, 3]

Since list.extend() accepts an arbitrary iterable, you can also replace

for line in mylog:
list1.append(line)

by

list1.extend(mylog)

All combinations of a list of lists

you need itertools.product:

>>> import itertools
>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> list(itertools.product(*a))
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]


Related Topics



Leave a reply



Submit