I have my array is : Li = [[1,2,3],[4,5,6],[7,8,9]] how can check if value exist in an array . Example
if 5 exist in Li return Li[1][1] so I can change the value of that item by making Li[1][1]=
"X"
If your nested list is always a 2D matrix of numbers, then you can find the indices fairly easily:
def find_indices(nested_list, value):
for i, inner_list in enumerate(nested_list):
for j, item in enumerate(inner_list):
if item == value:
return (i,j) # return a tuple containing the indices
Li = [[1,2,3],[4,5,6],[7,8,9]]
print(find_indices(Li, 5))
This example uses the enumerate function in Python, which gives you the index and item inside of an iterable object.
To be honest it is hard to understand what u really want, or if u urself even know that. Here is some input that might help u:
from typing import List
def is_value_in_list_of_lists(
value_to_check: int, list_of_lists: List[List[int]]
) -> bool:
for v in list_of_lists: # v::List[int]
if value_to_check in v:
return True
return False
def replace_all_occurrences_of_value_in_list_of_lists(
value_to_check: int, value_to_replace_with: str, list_of_lists: List[List[int]]
) -> List[List[int]]:
if is_value_in_list_of_lists(value_to_check, list_of_lists):
modified_list_of_lists = []
for v in list_of_lists: # v::List[int]
if value_to_check not in v:
modified_list_of_lists.append(v)
else:
# modify list
v_modified = []
for val in v: # val::int
if val == value_to_check:
v_modified.append(value_to_replace_with)
else:
v_modified.append(val)
modified_list_of_lists.append(v_modified)
return modified_list_of_lists
else:
return list_of_lists
if __name__ == "__main__":
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# True
print(is_value_in_list_of_lists(5, lists))
# [[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
print(replace_all_occurrences_of_value_in_list_of_lists(5, "X", lists))
# oneliner
# [[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
print(list([*map(lambda x: "X" if x == 5 else x, y)] for y in lists))
Related
I want to check for a certain condition list and then print it
suppose i want to check items of a in b
I want to check for values of list "a" in list "b" so i used this code
a=[1,2]
b=[1,2,3,4,5,6,7,8,9,]
c=[]
for i in a:
for j in b:
if i!=j:
c.append(j)
but i am getting infinite loop when i run this code code please help me.
It is unclear what behavior you would like to implement, but I guess you want to filter out elements in b that appear in a. If so, you can do this:
a = [1, 2]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
c = []
for i in b:
if not i in a:
c.append(i)
print(c)
The result:
[3, 4, 5, 6, 7, 8, 9]
**If you want to recover
identical elements in each list then try this code:**
c = []
def list_contains(a, b):
for x in a:
for y in b:
if x == y:
c.append(x)
continue
return c
a = [1, 2]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
print(list_contains(a, b))
Let's use some list comprehension!
I'll rename your lists:
list_a = [1, 2]
list_b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
So you want a list of everything in list_b...
result = [elem for elem in list_b] # (this just copies the list)
...where the element is also in list_a:
result = [elem for elem in list_b if elem in list_a]
...where the element is not in list_a:
result = [elem for elem in list_b if elem not in list_a]
Alternatively, make a function and use filter:
def keep_b_if(b_elem):
return b_elem in list_a
# or
return b_elem not in list_a
result = filter(keep_b_if, list_b)
Also, if a is just a collection of values to preserve/lose from b, it can be a set instead of a list:
forbidden = {1, 2}
...
if elem not in forbidden:
...
This question already has answers here:
Python3: How can I split a list based on condition?
(2 answers)
Closed last year.
I have a list like
a=['a',2,'[abcd]','bb',4,5,'kk','[efgh]',6,7,'no','[ijkl]',4,5,'lo']
So here we want group by after each '[]'
so the expected one would be
[['a',2],{'abcd': ['bb',4,5,'kk']},{'efgh': [6,7,'no']},{'ijkl': [4,5,'lo']}]
Any help would be appriciable
You can use groupby:
from itertools import groupby
a=['a',2,'[abcd]','bb',4,5,'kk','[efgh]',6,7,'no','[ijkl]',4,5,'lo']
def group_by_tag(li):
def tag_counter(x):
if isinstance(x, str) and x.startswith('[') and x.endswith(']'):
tag_counter.cnt += 1
return tag_counter.cnt
tag_counter.cnt = 0
return groupby(li, key=tag_counter)
Which you can use to make a list of tuples for each segment partitioned by the [tag]:
>>> x=[(k,list(l)) for k, l in group_by_tag(a)]
>>> x
[(0, ['a', 2]), (1, ['[abcd]', 'bb', 4, 5, 'kk']), (2, ['[efgh]', 6, 7, 'no']), (3, ['[ijkl]', 4, 5, 'lo'])]
And then create your desired mixed-type list from that:
>>> [v if k==0 else {v[0].strip('[]'):v[1:]} for k,v in x]
[['a', 2], {'abcd': ['bb', 4, 5, 'kk']}, {'efgh': [6, 7, 'no']}, {'ijkl': [4, 5, 'lo']}]
But consider that it is usually better to have a list of the same type of object to make processing that list easier.
If you want that, you could do:
>>> [{'no_tag':v} if k==0 else {v[0].strip('[]'):v[1:]} for k,v in x]
[{'no_tag': ['a', 2]}, {'abcd': ['bb', 4, 5, 'kk']}, {'efgh': [6, 7, 'no']}, {'ijkl': [4, 5, 'lo']}]
By "=>" I assume you want a dictionary if there is a preceding keyword and key be the word enclosed within the square brackets (if that's not what you intended feel free to comment and I'll edit this post)
import re
def sort(iterable):
result = {}
governing_match = None
for each in list(iterable):
match = re.findall(r"\[.{1,}\]", str(each))
if len(match) > 0:
governing_match = match[0][1:-1]
result[governing_match] = []
continue
result[governing_match].append(each)
return result
a=['[foo]', 'a' , 2 ,'[abcd]','bb',4,5,'kk','[efgh]',6,7,'no','[ijkl]',4,5,'lo']
for (k, v) in sort(a).items():
print(f"{k} : {v}")
Result :
foo : ['a', 2]
abcd : ['bb', 4, 5, 'kk']
efgh : [6, 7, 'no']
ijkl : [4, 5, 'lo']
The limitation of this is that every sequence should start with an element that is enclosed within square brackets.
You can use pairwise for that:
from itertools import pairwise
a=['a',2,'[abcd]','bb',4,5,'kk','[efgh]',6,7,'no','[ijkl]',4,5,'lo']
bracket_indices = [i for i, x in enumerate(a) if isinstance(x, str)
and x.startswith('[') and x.endswith(']')]
bracket_indices.append(len(a))
output = [a[:bracket_indices[0]]] # First item is special cased
output.extend({a[i][1:-1]: a[i+1:j]} for i, j in pairwise(bracket_indices))
I am learning pyspark from write a page rank program.
But when I use for loop to compute, every iteration is getting slower.
I try to use cache, but it seems don't work.
I have no idea how to fix this problem.
Here is my loop code
from time import time
for idx, i in tqdm(enumerate(range(10))):
start_time = time() # <-- start timing
new_values = stochastic_matrix.flatMap(lambda x: get_new_value(x, beta, N))
new_values = new_values.reduceByKey(add).map(lambda x: [x[0], x[1] + ((1-beta)/N)] )
S = new_values.values().reduce(add)
new_stochastic_matrix = stochastic_matrix.fullOuterJoin(new_values)
stochastic_matrix = new_stochastic_matrix.map(lambda x: sum_new_value(x, S, N))
new_stochastic_matrix.cache()
stochastic_matrix.cache() # <--- cache here
end_time = time()
print(idx, end_time - start_time)
sorted(stochastic_matrix.collect())[:10]
Update
After I comment this line
stochastic_matrix = new_stochastic_matrix.map(lambda x: sum_new_value(x, S, N))
It work normal !!
But I still don't know why and how to fix it.
Update 2
I set S as a constant, the speed is normal.
But I still don't know why and how to fix it.
All Flow
After Input Data
variable: stochastic_matrix - data struct looks like this.
[
(key,[value, this_node_connect_to_which_node]),
(1, [0.2, [2, 3]]),
(2, [0.2, [4]]),
(3, [0.2, [1, 4, 5]]),
(4, [0.2, []]),
(5, [0.2, [1, 4]])
]
Map
def get_new_value(item, beta, N):
key, tmp = item
value, dest = tmp
N_dest = len(dest)
new_values = []
for i in dest:
new_values.append([i, beta * (value/ N_dest)] )
return new_values
new_values = stochastic_matrix.flatMap(lambda x: get_new_value(x, beta, N))
new_values.collect()
########### output
[node, each_node_new_value]
[[2, 0.08000000000000002],
[3, 0.08000000000000002],
[4, 0.16000000000000003],
[1, 0.05333333333333334],
[4, 0.05333333333333334],
[5, 0.05333333333333334],
[1, 0.08000000000000002],
[4, 0.08000000000000002]]
Reduce by key
beta and N is just a float number
new_values = new_values.reduceByKey(add).map(lambda x: [x[0], x[1] + ((1-beta)/N)] )
new_values.collect()
###### Output
[[2, 0.12000000000000001],
[3, 0.12000000000000001],
[4, 0.33333333333333337],
[1, 0.17333333333333334],
[5, 0.09333333333333332]]
Combine new_values and stochastic_matrix
new_stochastic_matrix = stochastic_matrix.fullOuterJoin(new_values)
new_stochastic_matrix.collect()
#### Output
# (key, ([value, this_node_connect_to_which_node], new_value))
[(2, ([0.2, [4]], 0.12000000000000001)),
(4, ([0.2, []], 0.33333333333333337)),
(1, ([0.2, [2, 3]], 0.17333333333333334)),
(3, ([0.2, [1, 4, 5]], 0.12000000000000001)),
(5, ([0.2, [1, 4]], 0.09333333333333332))]
Update new_value to value
S and N are just a number
def sum_new_value(item, S, N):
key, value = item
if value[1] == None:
new_value = 0 + (1-S)/N
else:
new_value = value[1] + (1-S)/N
# new_value = value[1]
return [key, [new_value, value[0][1]]]
stochastic_matrix = new_stochastic_matrix.map(lambda x: sum_new_value(x, S, N))
sorted(stochastic_matrix.collect())[:10]
######## Output
[[1, [0.2053333333333333, [2, 3]]],
[2, [0.152, [4]]],
[3, [0.152, [1, 4, 5]]],
[4, [0.36533333333333334, []]],
[5, [0.1253333333333333, [1, 4]]]]
I am trying to append permutations of a list of integers to a local variable in python but end of appending a single permutation several times. The code will print all the results correctly but not sure why my class variable will not be updated correctly.
Any help would be extremely appreciated!!
I am working on a leetCode problem but can't output the right results. I am trying to update my array, myVals, within a backtracking loop but and storing the just one permutation.
I can print all the results however when
class Solution:
def __init__(self):
self.myVals = []
def add(self, x):
self.myVals.append(x)
def permuteArray(self, nums, l, r):
if l == r:
print(nums)
self.add(nums)
else:
for i in range(l, r + 1):
nums[l], nums[i] = nums[i], nums[l]
self.permuteArray(nums, 1+l, r)
nums[l], nums[i] = nums[i], nums[l]
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
numCount = len(nums)
start = 0
self.permuteArray(nums, start, numCount - 1)
print(self.myVals)
nums = [1,2,3]
driver = Solution()
result = driver.permute(nums)
Expected Results:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]
Actual Results:
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
Okay, so I have this function that I need to create and I think the code checker is somehow flawed and I tried manage it but my code still seems to fail
def reversecomp(L):
""" assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
if L == []:
return L
elif type(L) == int:
return L
else:
return reversecomp(L[1:]) + [reversecomp(L[0])]
def run_code(L):
return reversecomp(L)
print(L)
The question states that you need to mutate L. Your code must work when you do this:
L = [[0, 1, 2], [1, 2, 3], [3, 2, 1], [10, -10, 100]]
reversecomp(L)
print(L)
Test: run_code([[0, 1, 2], [1, 2, 3]])
Your output:
[[3, 2, 1], [2, 1, 0]]
Correct output:
[[3, 2, 1], [2, 1, 0]]
None
The spec says "It does not return anything"; your program does.
L is a list of lists of ints
Okay, so why are you checking type(L) == int when type(L) == list is always true, per the specification?
Mutates L
You're not mutating L at all; you're returning a new list. Mutating L means doing something like L[...] = xxx.
It does not return anything.
You shouldn't be using the return keyword at all in reversecomp.