Related
I have this code:
lokk = []
nums = 7
for _ in range(nums):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lokk.append(inner)
time.sleep()
print(lokk)
which provides me with this data:
['1', '2', '3', '4', '5', '6', '7']
what I want to do is to save that data into two different lists, the first list containing the first six values e.g. ['1', '2', '3', '4', '5', '6'] and the second lists containing the the whole seven values e.g. ['1', '2', '3', '4', '5', '6', '7'] how ever i want it be so that the next sample of data collected contains the last value of the second list as the first value of the list pair of lists like so ['7', '8', '9', '10', '11', '12', '13']
i thought this was the code that would somewhat enable be to get the data in the different lists like i wanted but then soon realized that by the time it goes to fetch the second set of data for the second list of seven values, the data would have changed and that's not what I want
lok = []
num = 6
for _ in range(num):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lok.append(inner)
time.sleep(10)
print(lok)
lokk = []
nums = 7
for _ in range(nums):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lokk.append(inner)
time.sleep()
print(lokk)
Another flaw i saw in this is that when it was time to run the process again later, the seventh data would not be the first data for the new set of lists.
Meaning that instead of:
listA = ['1', '2', '3', '4', '5', '6']
listB = ['1', '2', '3', '4', '5', '6', '7']
ListC = ['7', '8', '9', '10', '11', '12']
listD = ['7', '8', '9', '10', '11', '12', '13']
it would be:
listA = ['1', '2', '3', '4', '5', '6']
listB = ['1', '2', '3', '4', '5', '6', '7']
ListC = ['8', '9', '10', '11', '12', '13']
listD = ['8', '9', '10', '11', '12', '13', '14']`
I really hope I was clear enough in what I am looking for assistance in, if not please let me know.
Please help :(
You can achieve this in many ways, try this:
For ListC:
lok_c = []
num_c = 13
for _ in range(num_c):
inner = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").
get_attribute("innerHTML")
if num_c > 7:
lok_c.append(inner)
time.sleep()
print(lok_c)
For ListD:
lok_d = []
num_d = 14
for _ in range(num_d):
inner = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").
get_attribute("innerHTML")
if num_d > 7:
lok_c.append(inner)
time.sleep()
print(lok_d)
Correct the indentation and variable name, if I missed anything.
def convert_to_list(VertexList):
VerticesList = []
items = VertexList.split(';')
for item in items:
i = item.split(',')
SubList = []
for item in i:
SubList.append(item)
VerticesList.append(SubList)
return VerticesList
This code converts string in this format to a 2D list. However, I am sure it can be optimized.
Input -> '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
Output -> [['1', '2', '4', '5', '6', '7'], ['2', '3', '4', '5', '6', '7', '8'], ['1', '2', '4', '5', '6', '8']]
Use a comprehension.
inp = '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
print([s.split(',') for s in inp.split(';')])
Results in
[['1', '2', '4', '5', '6', '7'], ['2', '3', '4', '5', '6', '7', '8'], ['1', '2', '4', '5', '6', '8']]
This is smaller, easier to read code, which is part of the optimization I expect you were looking for. It doesn't loop through things any fewer times, but it's executing fewer assignments, using less temporary variabels, and making fewer function calls (i.e. append()). Maybe some of those calls are being made behind the scenes in the comprehension, but you should be taking advantage of whatever optimizations Python does to its comprehensions in terms of what functions calls are made.
--update--
Check out this answer for a performance analysis of the OP and this answer.
-- update 2 --
To convert all strings to int, you can use map or another comprehension.
inp = '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
print([list(map(int, s.split(','))) for s in inp.split(';')])
or
inp = '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
print([[int(c) for c in s.split(',')] for s in inp.split(';')])
This is not a solution, but only a comparison of the optimality of the above codes in terms of actual performance:
from timeit import Timer
code1 = """\
def convert_to_list(VertexList):
VerticesList = []
items = VertexList.split(';')
for item in items:
i = item.split(',')
SubList = []
for item in i:
SubList.append(item)
VerticesList.append(SubList)
return VerticesList
inp = '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
convert_to_list(inp)
"""
code2 = """\
inp = '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
out = [s.split(',') for s in inp.split(';')]
"""
t = Timer(stmt=code1)
time1 = t.timeit() # 1000000 iteration by default
print(f"Original time:{round(time1, 6)} sec.")
t = Timer(stmt=code2)
time2 = t.timeit() # 1000000 iteration by default
print(f"New time: {round(time2, 6)} sec.")
print(f'New solution faster in = {round(time1 / time2, 1)} times')
Output:
Original time:1.812856 sec.
New time: 0.741987 sec.
New solution faster in = 2.4 times
I'm trying to get a list to rotate, add a variable to the end, and the next time the function is called, the list rotates again ect etc. How ever, when I implement this code, the list doesn't rotate every time the function is ran.
var1 = "1";
var2 = "2";
var3 = "3";
var4 = "4";
var5 = "5";
check = [var1, var2, var3, var4, var5]
def checkIfExists(checkList):
var = input();
if var not in checkList:
check = checkList[1:] + checkList[:1]
check.append(var)
check.pop(1)
check = checkList[2:] + checkList[:2]
print(check)
its entirely possible I'm just goofing up and messing up somewhere, but I'm stuck. Any help?
def checkIfExists(checkList):
print('Input new number:')
var = input()
if var not in checkList:
check.pop(0)
check.append(var)
print('return new check:')
print(check)
test result:
>>> check = ['1', '2', '3', '4', '5']
>>> checkIfExists(check)
Input new number:
6
return new check:
['2', '3', '4', '5', '6']
>>> checkIfExists(check)
Input new number:
7
return new check:
['3', '4', '5', '6', '7']
If you move the input() outside the function it's easier to communicate the problem:
def checkIfExists(list, var):
if var not in list:
# assumes list is not empty
list.pop(0)
list.append(var)
return list
check = ['1', '2', '3', '4', '5']
for var in ['6', '7']:
check = checkIfExists(check, var)
print(check)
Will give you this output:
['2', '3', '4', '5', '6']
['3', '4', '5', '6', '7']
I have 3 arrays with same customer names in different orders, what I am trying to do and the following:
1 - Take the name of customers and compare to return when it is the same, thus solving the problem of random order;
2 - After obtaining this comparison, the output should be as follows:
Result: CLIENT1, '2', '3', '2', '3', '2', '3'
...
The output should look like this: Client Name, value contained within array1 for this client name, value contained within array2 for this client name and value contained within array3 for this client name
Problem: I can not perform this operation with 3 arrays, only 2, besides, I am having difficulty formatting the output in the established pattern
ARRAYS
######################################################################################
# Create arrays
######################################################################################
array1 = [['CLIENT1', '2', '3'],['CLIENT2', '3', '4'],['CLIENT3', '4', '5']]
array2 = [['CLIENT3', '2', '3'],['CLIENT2', '3', '4'],['CLIENT1', '4', '5']]
array3 = [['CLIENT2', '2', '3'],['CLIENT1', '3', '4'],['CLIENT3', '4', '5']]
SEARCH
######################################################################################
# Check and align
######################################################################################
for line1 in array1:
for line2 in array2:
if line1[0].upper().__contains__(line2[0].upper()):
# print of results
I suggest using an intermediate dictionary to store the values of every processed client. Using this structure you can store any information from the clients (with repetitions or without) and you can easily parse the output.
Here is the code:
# Initialize values
array1 = [['CLIENT1', '2', '3'], ['CLIENT2', '3', '4'], ['CLIENT3', '4', '5']]
array2 = [['CLIENT3', '2', '3'], ['CLIENT2', '3', '4'], ['CLIENT1', '4', '5']]
array3 = [['CLIENT2', '2', '3'], ['CLIENT1', '3', '4'], ['CLIENT3', '4', '5']]
# Initialize a dictionary with key = client name, value = list of client entries
result = {}
# Add values from array1
for client_info in array1:
# Parse current entry
client_name = client_info[0]
client_values = client_info[1:]
# Add previous values if exitant
if client_name in result.keys():
client_values.extend(result[client_name])
# Update clients dictionary
result[client_name] = client_values
# Add values from array2
for client_info in array2:
# Parse current entry
client_name = client_info[0]
client_values = client_info[1:]
# Add previous values if exitant
if client_name in result.keys():
client_values.extend(result[client_name])
# Update clients dictionary
result[client_name] = client_values
# Add values from array3
for client_info in array3:
# Parse current entry
client_name = client_info[0]
client_values = client_info[1:]
# Add previous values if exitant
if client_name in result.keys():
client_values.extend(result[client_name])
# Update clients dictionary
result[client_name] = client_values
# Print result information
for client_name, client_values in result.items():
print("Result: " + str(client_name) + ", " + str(client_values))
And the obtained output:
Result: CLIENT1, ['3', '4', '4', '5', '2', '3']
Result: CLIENT2, ['2', '3', '3', '4', '3', '4']
Result: CLIENT3, ['4', '5', '2', '3', '4', '5']
If you are willing to display ONLY the clients that appear on the 3 lists, you can avoid updating the result dictionary on the array2 and array3 loops when the client name is not on the list.
array1 = [['CLIENT1', '2', '3'],['CLIENT2', '3', '4'],['CLIENT3', '4', '5']]
array2 = [['CLIENT3', '2', '3'],['CLIENT2', '3', '4'],['CLIENT1', '4', '5']]
array3 = [['CLIENT2', '2', '3'],['CLIENT1', '3', '4'],['CLIENT3', '4', '5']]
def search(key, arrays):
result = []
for array in arrays:
for lst in array:
if lst[0] == key:
result.extend(lst[1:])
return 'Result: {key}, {values}'.format(key=key, values=', '.join(result))
print(search('CLIENT1', (array1, array2, array3)))
Output:
Result: CLIENT1, 2, 3, 4, 5, 3, 4
i have list like
list = ['1,2,3,4,5', '6,7,8,9,10']
I have problem with "," in list, because '1,2,3,4,5' its string.
I want to have list2 = ['1','2','3','4'...]
How i can do this?
Should be something like that:
nums = []
for str in list:
nums = nums + [int(n) for n in str.split(',')]
You can loop through and split the strings up.
list = ['1,2,3,4,5', '6,7,8,9,10']
result = []
for s in list:
result += s.split(',')
print(result)
Split each value in the original by , and then keep appending them to a new list.
l = []
for x in ['1,2,3,4,5', '6,7,8,9,10']:
l.extend(y for y in x.split(','))
print(l)
Use itertools.chain.from_iterable with map:
from itertools import chain
lst = ['1,2,3,4,5', '6,7,8,9,10']
print(list(chain.from_iterable(map(lambda x: x.split(','), lst))))
# ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Note that you shouldn't use list name for variables as it's a built-in.
You can also use list comprehension
li = ['1,2,3,4,5', '6,7,8,9,10']
res = [c for s in li for c in s.split(',') ]
print(res)
#['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
list2 = []
list2+=(','.join(list).split(','))
','.join(list) produces a string of '1,2,3,4,5,6,7,8,9,10'
','.join(list).split(',') produces ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
join method is used to joined elements in a list by a delimiter. It returns a string in which the elements of sequence have been joined by ','.
split method is used to split a string into a list by a delimiter. It splits a string into an array of substrings.
# Without using loops
li = ['1,2,3,4,5', '6,7,8,9,10']
p = ",".join(li).split(",")
#['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']