logo
down
shadow

Conditional statment regarding various regex and length of a list in python


Conditional statment regarding various regex and length of a list in python

By : Xiaolv
Date : November 21 2020, 11:01 PM
Any of those help I have following list : , This is one possible way:
code :
lists = [['E12.2', 'E16.1', 'E15.1'],
         ['E10.1', 'I11.2', 'I10.1_27353757'],
         ['E16.1', 'E18.1', 'E17.3'],
         ['E1.8', 'I12.1_111682336', 'I12.1_111682195'],
         ['E55.1', 'E57.1', 'E56.1','E88.1'],
         ['U22.3', 'U22.6_13735517', 'U23.1']]

for lst in lists:
    if len(lst) != 3 and not any('_' in item or 'U' in item for item in lst):
        print(lst)

# Output:
# ['E55.1', 'E57.1', 'E56.1', 'E88.1']
from collections import Counter
import re

lists = [['E12.2', 'E16.1', 'E15.1'],
         ['E10.1', 'I11.2', 'I10.1_27353757'],
         ['E16.1', 'E18.1', 'E17.3'],
         ['E1.8', 'I12.1_111682336', 'I12.1_111682195'],
         ['E55.1', 'E57.1', 'E56.1','E88.1'],
         ['U22.3', 'U22.6_13735517', 'U23.1'],
         ['E7.2', 'E9.5', 'E9.3']]

for lst in lists:
    if (len(lst) != 3 and not any('_' in item or 'U' in item for item in lst) and
            (Counter(match.groups(1) for match in [re.match(r'E(\d+)\.', item) for item in lst] if match is not None)
             .most_common(1) or [(None, 1)])[0][1] == 1):
        print(lst)

# Output:
# ['E55.1', 'E57.1', 'E56.1', 'E88.1']


Share : facebook icon twitter icon
Python List comprehension to create unequal length lists from a list using conditional

Python List comprehension to create unequal length lists from a list using conditional


By : David Kocinski
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Using list comprehension, itertools or similar functions, is it possible to create two unequal lists from a list based on a conditional? Here is an example: , A true itertools-based solution that works on an iterable:
code :
>>> part_iter = iter(part_list)
>>> part_in, part_out = itertools.tee(part_iter)
>>> in_main = (p for p in part_in if p in main_list)
>>> out_main = (p for p in part_out if p not in main_list)
>>> list(in_main)
[4, 1]
>>> list(out_main)
[5, 2, 7]
>>> main_set = set(main_list)
>>> in_main = []
>>> out_main = []
>>> for p in part_list:
...     (in_main if p in main_set else out_main).append(p)
... 
>>> in_main
[4, 1]
>>> out_main
[5, 2, 7]
>>> import collections
>>> in_out = collections.defaultdict(list)
>>> for p in part_list:
...     in_out[p in main_list].append(p)
... 
>>> in_out
defaultdict(<type 'list'>, {False: [5, 2, 7], True: [4, 1]})
Replacing variable length items in a list using regex in python

Replacing variable length items in a list using regex in python


By : Rajiv Srivastava
Date : March 29 2020, 07:55 AM
This might help you I think your solution is quite to complicated. This one should do the job and is much simpler:
code :
import re

def repl(match):
    return match.group(1) + ("0"*7) + match.group(2)

print re.sub(r"(HD)([1-9]{1}[0-9]{5})", repl, "HD479659")
import re

values_to_transform = [
    'HD479659',
    'HD477899',
    'HD423455',
    'does not match',
    'but does not matter'
]

def repl(match):
    return match.group(1) + ("0"*7) + match.group(2)

for value in values_to_transform:
    print re.sub(r"(HD)([1-9]{1}[0-9]{5})", repl, value)
HD0000000479659
HD0000000477899
HD0000000423455
does not match
but does not matter
Read column of text data and do the conditional statment in python

Read column of text data and do the conditional statment in python


By : Anu Tanskanen
Date : March 29 2020, 07:55 AM
wish of those help First you open the file, and save the content between PFAF and END OF DISPLAY into a pandas DataFrame (just in case you need to do other operations on your data.
Then, you iterate over this DataFrame, when the row of column D is > 30 you save the index, and exit the for loop using a break
code :
import pandas as pd

CREATE_TAB_MODE = 0
DF_INDEX = None
df_columns = None
df_list = []

with open('your_file.txt') as f:
    for line in f:
      if line.startswith('PFAF'):
        CREATE_TAB_MODE = 1
      elif line.startswith('END OF DISPLAY'):
        break
      elif CREATE_TAB_MODE:
        if df_columns is None:
          df_columns = line.strip().split()
        else:
          df_list.append(line.strip().split())


df = pd.DataFrame(df_list, columns=df_columns)

for index, row in df.iterrows():
  if int(row['D']) > 30:
    DF_INDEX = index
    break

print(df[DF_INDEX:])
is there a way to convert the ?: operator in a string to python conditional statment?

is there a way to convert the ?: operator in a string to python conditional statment?


By : Naudy J
Date : March 29 2020, 07:55 AM
I hope this helps you . How about using a regex? This particular regex doesn't care about spaces and is using named capture groups for clarity
code :
import re

regex = re.compile(r'\((?P<cond>.*)\) ?\? ?(?P<if_true>.+):(?P<if_false>.+)')

string = '(l3>=l4) ? k2:k3'
match = regex.search(string)
print('{if_true} if {cond} else {if_false}'.format(if_true=match.group('if_true'),
                                                   cond=match.group('cond'),
                                                   if_false=match.group('if_false')))

# k2 if l3>=l4 else k3
Conditional regex php with limited length

Conditional regex php with limited length


By : Satvik
Date : March 29 2020, 07:55 AM
I hope this helps you . When you need to match multiple characters with a regex, you should use limiting quantifiers - and you did. However, when you need to **restrict the length to N characters matched, you should use zero width assertions.
Since your problem is matching entire strings, you need the anchors: ^ and $ (end of string). When validating, I'd rather recommend \A instead of ^ and \z (that only matches at the end of the string) instead of $ (that may match before the last newline).
Related Posts Related Posts :
  • Django Form Based on Variable Attributes
  • Relocate all the evens
  • How to scrap span ids' texts in beautifulsoup in the following html?
  • How to generate random number in a given range as a Tensorflow variable
  • Gradient Descent Variation doesn't work
  • Python 2.7 - search for a particular URL on a webpage with ajax
  • How to configure Luigi task retry correctly?
  • web.py : an urlencoded slash into args
  • Use of pyzmq's logging handler in python
  • How to count the number of a particular entry. python
  • devide int into lower whole ints
  • Access atribute of every object in pandas dataframe column
  • Combine Dataframe rows on conditions
  • Select closest date (or value) in pandas / python
  • Pycharm and remote interpreter (Docker) shows errors but runs fine
  • Get started to launch google-cloud-ml with my own dataset
  • Multiprocessing: use only the physical cores?
  • Django Login Custom Auth works locally but not on production server
  • Python: Invalid HTTP basic authentication header with long base64 string
  • How can I request several pages without wating for the output?
  • Flask Response vs Flask make_response
  • python linear regression predict by date
  • How to get pandas dataframe where columns are the subsequent n-elements from another column dataframe?
  • MYSQL: "Access denied for user 'X'@'localhost' (using password: YES)" PYTHON
  • install scipy package via pycharm in windows 10 64 bit - python 3.5
  • Update time in linux and solaris machines from robot framework
  • Complex pandas isin function
  • Averaging over every n elements of an array without numpy
  • An elegant way of inserting multiple arguments
  • IntegrityError:NOT NULL constraint failed: chatapp_chat.message
  • Indexing of 3d numpy arrays with 2d arrays
  • Creating a mean of columns with csv writer
  • Reading in environment variables from an environment file
  • Collapse duplicate rows with pandas
  • How can I use skyfied to convert SGP4 TEME coordinate to ECEF?
  • How to modify object in Python's Rtree index
  • Create Hexbin plot with pandas dataframe using index and columns names as x and y
  • SQLAlchemy query returns no data if a database field is empty
  • Python pandas column asignment between dataframe and series does not work
  • ValueError: Unknown label type: array while using Decision Tree Classifier and using a custom dataset
  • Trouble accessing exif information with PIL.Image._getexif()
  • Use all coordinates in a grid except with certain value
  • Why for loop is splitting strings of user input?
  • How can I add two variable and assign to result variable in Python?
  • Error when parsing timestamp with pandas read_csv
  • Slicing arrays based on boolean array in python
  • Feeding scipy.sparse() sparse matrices into CVXOPT
  • How to separate a irregularly cased string to get the words? - Python
  • Pandas: replace some values in column if that contain a substring
  • Fabric does not close the ssh connection
  • Python Creating Classes Code
  • When will train() method in easy_seq2seq stop?
  • How to split each element of the RDD in spark with python?
  • Read in csv file in python, round the values and write back to file
  • How to properly close a QWidget-window in an API with PythonQt
  • How to know which segment a value reside in
  • pandas: convert multiple categories to dummies
  • 'Options' object has no attribute 'get_all_field_names'
  • Customize django filter model field
  • NLTK tag Dutch sentence
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com