  C RUBY-ON-RAILS MYSQL ASP.NET DEVELOPMENT RUBY .NET LINUX SQL-SERVER REGEX WINDOWS ALGORITHM ECLIPSE VISUAL-STUDIO STRING SVN PERFORMANCE APACHE-FLEX UNIT-TESTING SECURITY LINQ UNIX MATH EMAIL OOP LANGUAGE-AGNOSTIC VB6 MSBUILD # Python - Iterative self cross referencing  » python » Python - Iterative self cross referencing

By : StevenLavinske
Date : November 22 2020, 10:40 AM
I wish this helpful for you I have a bit of a logical challenge. I have a single table in excel that contains an identifier column and a cross reference column. There can be multiple rows for a single identifier which indicates multiple cross references. (see basic example below) code :
``````t = [
["a1","a2"],
["a1","a3"],
["a1","ax"],
["ax","b1"],
["ax","bx"],
["bx","b3"]
]

import itertools
def find_matches(t,key):
return list(itertools.chain(*[[v] if not v.endswith("x") else find_matches(t,v) for k,v in t if k == key]))

print find_matches(t,"a1")
``````
``````t = [
["a1","a2"],
["a1","a3"],
["a1","ax"],
["ax","b1"],
["ax","bx"],
["bx","b3"]
]
class MyGraph:
self.graph = {}
if from_node in self.graph:
self.graph[from_node].append(to_node)
else:
self.graph[from_node] = [to_node]
print self.graph
def find_leaves(self,v):
seen = set(v)
def search(v):
for vertex in self.graph[v]:
if vertex in seen:
continue
if vertex in self.graph:
for p in search(vertex):
yield p
else:
yield vertex
for p in search(v):
yield p

print list(MyGraph(t).find_leaves("a1"))#,"a1")
`````` ## Python Pandas Lookup/Cross Referencing

By : Ying-Chieh Jay Huang
Date : March 29 2020, 07:55 AM
it helps some times I have two data frames: , For (i) you just need to specify right join, and fill null values:
code :
``````>>> pd.merge(df1, df2, how='right').fillna(0)
word  score
0  laugh      7
1  frown     -3
2   play      0
``````
``````>>> def grpavg(ws):
...     i = df1['word'].isin(ws)
...     return df1.loc[i, 'score'].sum() / len(ws)
...
>>> df3['avg-score'] = df3['words'].str.split().map(grpavg)
>>> df3
words  avg-score
0             frown cry      -5.50
1           laugh smile       4.50
2            play laugh       3.50
3  cry laugh play smile       0.25
``````
``````>>> def grpavg(ws, df):
...     i = df['word'].isin(ws)
...     return df.loc[i, 'score'].sum() / len(ws)
...
>>> from functools import partial
>>> f = partial(grpavg, df=df1)
>>> df3['avg-score'] = df3['words'].str.split().map(f)
>>> df3
words  avg-score
0             frown cry      -5.50
1           laugh smile       4.50
2            play laugh       3.50
3  cry laugh play smile       0.25
`````` ## can there be 'cross-referencing' generators in Python?

By : user3856341
Date : March 29 2020, 07:55 AM
should help you out Imagine the following piece of code which generates a list of file sizes from the current directories' files: , You can do it like this:
code :
``````_sizes = [
getsize(join(_base, _file))
for _base, _dirs, _files in os.walk('.')
for _file in _files
]
``````
``````_sizes = (
getsize(join(_base, _file))
for _base, _dirs, _files in os.walk('.')
for _file in _files
)
`````` ## Cross Referencing Lists in Python

By : samathon
Date : March 29 2020, 07:55 AM
To fix this issue You can loop through each list in list_1 and check if the input is in one. If it is, you can print the corresponding index of list_2 (assuming it is composed only of single values), which you obtain by using enumerate in the loop.
code :
``````input = 1
for idx,i in enumerate(list_1):
if input in i:
return list_2[idx]
`````` ## Cross referencing two csv files in python

By : Karam Al-Raawy
Date : March 29 2020, 07:55 AM
To fix this issue The first thing you need to be aware of is that you can't update the file you are reading. Textfiles (which include .csv files) don't work like that. So you have to read the whole of Destinations.csv into memory, and then write it out again, under a new name, but skipping the rows you don't want. (You can overwrite your input file, but you will very quickly discover that is a bad idea.)
code :
``````import csv

blacklist_rows = []
with open('Black List.csv', 'r') as bl:
blacklist_rows.append(line)

destination_rows = []
with open('Destinations.csv', 'r') as dest:
destination_rows.append(line)
``````
``````with open('FilteredDestinations.csv', 'w') as output:
writer = csv.writer(output)
for r in destination_rows:
if not r:   # trap for blank rows in the input
continue
if r *matches something in blacklist_rows*: # you have to code this
continue
writer.writerow(r)
`````` ## Cross-referencing between two lists in Python?

By : Tiago Vieira
Date : October 04 2020, 09:00 PM
it helps some times You can use setdefault to accumulate the shopping list like:
Code
code :
``````users = {x['id']: x for x in a}
for x in b:
user = users[x['uid']]
user.setdefault('shoppinglist', []).append(x['item'])
result = [users[i['id']] for i in a]
``````
``````a = [
{
"id": 1,
"name": "John Mark",
"alias": "Batman",
},
{
"id": 2,
"name": "Luke Ben",
"alias": "Spider",
}
]

b = [
{
"uid": 1,
"item": "eggs",
"completed": False
},
{
"uid": 1,
"item": "milk",
"completed": False
},
{
"uid": 2,
"completed": False
},
{
"uid": 2,
"item": "cheese",
"completed": True
}
]

users = {x['id']: x for x in a}
for x in b:
user = users[x['uid']]
user.setdefault('shoppinglist', []).append(x['item'])
result = [users[i['id']] for i in a]

print(result)
``````
``````[
{'id': 1, 'name': 'John Mark', 'alias': 'Batman', 'shoppinglist': ['eggs', 'milk']},
{'id': 2, 'name': 'Luke Ben', 'alias': 'Spider', 'shoppinglist': ['bread', 'cheese']}
]
`````` 