Python Lists - find uncommon elements - python-3.x

I want to compare two lists in order to create a new list of specific elements found in one list but not in the other. I want the code to return all occurrences of unmatched values.
input:
list1=7,7,8,9
list2=8,9
desired output= 7,7
import numpy as np
list1 = input("Input list1 : ").split(",")
list2 = input("Input list list2 : ").split(",")
main_list = np.setdiff1d(list1,list2)
print(main_list)

You could do:
[i for i in list1 if i in (set(list1) - set(list2))]
using numpy:
import numpy as np
np.array(list1)[np.in1d(list1, np.setdiff1d(list1, list2))].tolist()

Related

Getting the elements of list in specific range in Python using negative indexing

Input
list1 = ['Apple','Google','MS','Facebook']
print(list1)
list1[-4:1]
Output
['Apple', 'Google', 'MS', 'Facebook']
['Apple']
Can anyone please explain the result?
When you use negative indexing, you start at index -1. It would seem silly to say list1[-0] and have it be different than list1[0]. Because of this your code becomes "grab the elements starting from the 4th to last and going to 1". Another way to think of it is list1[-4] is the same as list1[len(list1) - 4]. So for this you're going in the range [0, 1) and only returning the first element.
This may help you.
from math import sqrt
from sklearn.cluster import MiniBatchKMeans
import pandas_datareader as dr
from matplotlib import pyplot as plt
import pandas as pd
import matplotlib.cm as cm
import seaborn as sn
start = '2020-1-1'
end = '2021-1-1'
tickers = ['AXP','AAPL','BA','CAT','CSCO','CVX','XOM','GS']
prices_list = []
for ticker in tickers:
try:
prices = dr.DataReader(ticker,'yahoo',start)['Adj Close']
prices = pd.DataFrame(prices)
prices.columns = [ticker]
prices_list.append(prices)
except:
pass
prices_df = pd.concat(prices_list,axis=1)
prices_df.sort_index(inplace=True)
prices_df.head()
index -4 means 4th from last element, so list1[-4:1] is the same as list1[0:1], which is the same as [list1[0]] which is [`Apple`]
( To give another example, list1[1:-1] == list1[1:3] == [list1[1],list1[2]] == [`Google`,`MS`] )

calculation of distance matrix in a faster approach

I have a dataframe
import numpy as np
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
import pandas as pd
a = {'b':['cat','bat','cat','cat','bat','No Data','bat','No Data']}
df11 = pd.DataFrame(a,index=['x1','x2','x3','x4','x5','x6','x7','x8'])
and i have a distance function
def distancemetric(x):
list1 = x['b'].tolist()
result11 =[]
sortlist11 = [process.extract(ele, list1, limit=11000000, scorer=fuzz.token_set_ratio) for ele in list1]
d11 = [dict(element) for element in sortlist11]
finale11 = [(k, element123[k]) for k in list1 for element123 in d11]
result11.extend([x[1] for x in finale11])
final_result11=np.reshape(result11, (len(x.index),len(x.index)))
return final_result11
I call the funtion by
values1 = distancemetric(df11)
Here the token_set_ratio methods compares only two strings. When i pass an array of strings it gives me avg which i dont need.
This code is working but it is slower. Is there any way which could make it run faster

Create a set in Python and append the values from another list to it

I have list 2 which has all the items fron list 1 and x :
import random
for x in range(10):
print(random.randint(1,101))
list1 = ''
list.append(x)
list2 = list1
How can I create a set and add all the items from list 2 into a set? All the code up to this point is what I have been told to do and I have no idea how to create a set and append items to it.
Maybe something like this. I convert list to set in the end.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
list1 = []
for x in range(10):
number = random.randint(1,101)
list1.append(number)
list2 = list1
new_set = set(list2)
print (new_set)

how to format the variable x into format(platecode)

import string
with open('platenon.txt', 'w') as f:
for platecode in range(1000):
x =['A' + upper_char for upper_char in string.ascii_uppercase]
f.write('KJA{0:03d}'.format(platecode))
To get a list of all combinations of two letters from 'AA' to 'ZZ':
import string
import product
list(''.join(pair) for pair in itertools.product(string.lowercase, repeat=2))
If I understand you question correctly you want to get a list which contains the strings 'AA' - 'AZ' ['AA', 'AB', 'AC', ..., 'AZ']?
import string
upper_chars = ['A' + upper_char for upper_char in string.ascii_uppercase]
To get a list with all strings from 'AA' to 'ZZ' you can use this in python3
from string import ascii_uppercase
from itertools import product
[''.join(c) for c in product(string.ascii_uppercase, string.ascii_uppercase)]

Python 3.x random input for lists

from random import randint
List = [randint(0,99)*20]
print(List)
How could i go along the lines of make it into a list for 20 different random numbers between 0 and 99? The code i have ends up multiplying one random number 20 times.
You can use list comprehension:
List = [randint(0,99) for i in range(20)]
from random import randint
List = [randint(0,99) for i in range(20)]
print("%3s" % List)
List.sort()
print("%3s" % List)
My primary is Java. I hope this helps!

Resources