a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple

a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple

Content Index :

a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
Tag : python , By : hammer_1968
Date : January 12 2021, 01:40 AM

should help you out I have got a List of tuples of tuples like below: , you can try by using a defaultdict/dict:
from pprint import pprint
from collections import defaultdict

x = [
    (('102', '393', 'abc'), 63),
    (('102', '393', 'ack'), 8),
    (('117', '393', 'bcx'), 57),
    (('390', '393', 'wff'), 41),
    (('393', '102', 'wer'), 40),
    (('393', '102', 'wfv'), 78),
    (('393', '117', 'iyy'), 7),
    (('393', '448', 'wec'), 25),

val = defaultdict(list)

for item in x: 
    val[item[0][0], item[0][1]].append(item)

[[(('102', '393', 'abc'), 63), (('102', '393', 'ack'), 8)],
 [(('117', '393', 'bcx'), 57)],
 [(('390', '393', 'wff'), 41)],
 [(('393', '102', 'wer'), 40), (('393', '102', 'wfv'), 78)],
 [(('393', '117', 'iyy'), 7)],
 [(('393', '448', 'wec'), 25)]]
pprint([[e[1] for e in i] for i in val.values()])
[[63, 8], [57], [41], [40, 78], [7], [25]]

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

In a list of tuples, return tuple[1] if tuple[0] is a duplicate of another tuple[0] in the list

Tag : python , By : George Handlin
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You almost never want to use index on a list. Keep track of where you are while iterating; don't try to find your position again from the value.
In this case, what you really want is a "multidict", a dictionary that maps keys to collections of values. In this case, checksums to collections of names. Then, any checksum that maps to a set of more than 1 name, it's a dup, and the set is exactly the list of names you want to print out, so that's all it takes.
>>> pairs = [("sumstring1","abc.txt"), ("sumstring2","def.txt"),
...          ("sumstring1","ghi.txt"), ("sumstring2","jkl.txt")]
>>> dups = collections.defaultdict(set)
>>> for checksum, name in pairs:
...     dups[checksum].add(name)
>>> dups
defaultdict(<class 'set'>, {'sumstring1': {'ghi.txt', 'abc.txt'}, 'sumstring2': {'def.txt', 'jkl.txt'}})
>>> dups = {checksum: names for checksum, names in dups.items() if len(names) > 1}
>>> dups
{'sumstring1': {'abc.txt', 'ghi.txt'}, 'sumstring2': {'def.txt', 'jkl.txt'}}
>>> dups = list(dups.values())
>>> dups = [tuple(names) for names in dups.values()]
>>> dups
[('ghi.txt', 'abc.txt'), ('def.txt', 'jkl.txt')]

Append tuple elements to a tuple of tuples in Python

Tag : python , By : user135518
Date : March 29 2020, 07:55 AM
Does that help If I have a tuple, e.g. x = (1, 2, 3) and I want to append each of its elements to the front of each tuple of a tuple of tuples, e.g. y = (('a', 'b'), ('c', 'd'), ('e', 'f')) so that the final result is z = ((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f')), what is the easiest way? , Use zip and flatten the result:
>>> x = (1, 2, 3)
>>> y = (('a', 'b'), ('c', 'd'), ('e', 'f'))
>>> tuple((a, b, c) for a, (b, c) in zip(x,y))
((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f'))
>>> tuple((head, *tail) for head, tail in zip(x,y))
((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f'))

Combining tuple elements from a list of tuples. Tuple elements are tuple and list

Tag : python , By : General Mills
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You can basically loop along, remembering what is the current key (initialized to None).
key = None # This is 'A' or 'B' in your example, but it starts off as None
new_list = [] # This holds the final result
for r, l in [(r, l) for (l, r) in list_one]: 
    if r != key: # If the current is not the key, time to switch to a new one
        id_ = l[0]
        new_list.append({id_: []})
    new_list[-1][id_].extend(l[1]) # Extend the current list
    key = r # Make it the current key in any case.

>>> new_list
[{'id1': ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']},
 {'id3': ['v11', 'v12', 'v13', 'v14', 'v16']},
 {'id6': ['v17', 'v18', 'v21']}]

Remove tuple from list of tuples if tuple's elements aren't in a list of strings

Tag : python , By : George Handlin
Date : March 29 2020, 07:55 AM
Does that help I'm working on some code where I need to remove a tuple from a list of tuples if the tuple doesn't contain all strings in a separate list. I've got it working in a for loop, but I'm trying to improve the efficiency of my code. As an example, if I have , You can use all with a nested comprehension:
list_of_tups = [('R', 'S', 'T'), ('A', 'B'), ('L', 'N', 'E'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
needed_strings = ['R', 'S', 'T']

[t for t in list_of_tups if all(c in t for c in needed_strings)]
[('R', 'S', 'T'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
list_of_tups = [('R', 'S', 'T'), ('A', 'B'), ('L', 'N', 'E'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
needed_strings = set(['R', 'S', 'T'])

[t for t in list_of_tups if needed_strings.issubset(t)]

How to arrange a list of tuples so that the tuple associated with the highest value compared to other tuple is removed a

Tag : python , By : John R
Date : March 29 2020, 07:55 AM
wish of those help you could use sort according to the length of the list, and use a dictionary so the last written key "wins".
Then convert back to tuple or list or ... leave as dict:
val = [(200, []), (300, [500, 200]), (400, [100, 200, 300]), (400, [])]

def largest_val_arrangement(val):
    return tuple({k:v for k,v in sorted(val, key = lambda t : len(t[1]))}.items())

((200, []), (400, [100, 200, 300]), (300, [500, 200]))
def largest_val_arrangement(val):
    d = dict()
    for k,v in val:
        if k not in d or len(d[k]) < len(v):
            d[k] = v

    return tuple(d.items())
Related Posts Related QUESTIONS :
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • Display image of 2D Sinewaves in 3D
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • Detect if user has clicked the 'maximized' button
  • Does flask_login automatically set the "next" argument?
  • Indents in python 3
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • a thread python with 'while' got another thread never start
  • Solution from SciPy solve_ivp contains oscillations for a system of first-order ODEs
  • trigger python events driven by selenium controlled browser
  • Passing line-edits to a contextmanager to set validators
  • Python: globals().items() iterations try to change a dict
  • Is it possible to specify starting values for each parameter (instead of bounds) for scipy's differential evolution?
  • why datetime.now() and constructed datetime using all fields(like year,month...) of now has big timedelta?
  • MySQL multiple table UPDATE query using sqlalchemy core?
  • find if a semantic version is superset of of another version python
  • Type checking against dynamically created objects
  • Struggling with simple reverse function
  • Is there a function for finding the midpoint of n points on sklearn.neighbors.NearestNeighbors?
  • How to set max number of tweets to fetch
  • PYTHON 3.7.4 NOT USING SQLITE 3.29.0
  • How to replace Nan value with zeros in a numpy array?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com