Count Single Words in Python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
So I need to count individual words (specifically red and blue) in a python inputted list.
However, it cannot be for instance redish or bluemaybe.
Here's what I've done (I've tried if loops to catch it but hasn't worked.)
r = 0
b = 0
cars = []
car = input("Cars: ")
cars.append(car)
car.split()
r = car.count('red')
b = car.count('blue')
print("red:",r)
print("blue:",b)

The following works.
# replace by 'carsStr = input("Cars: ")' if you wish
carsStr = "rad blue blueish redish red blue red"
# str.split() returns a list of strings, never in-place
cars = carsStr.split()
r = cars.count('red')
b = cars.count('blue')
print("red:",r)
print("blue:",b)
Here are your mistakes:
Doing cars.append(car) and then car.split() doesn't "expand" the car string in the cars list.
car.split() doesn't happen in-place, it returns a list of strings. In your case, that list is lost since you don't assign it to a variable.
You also never reuse the cars list.
If you wan't a more complete counting tool see https://docs.python.org/3/library/collections.html#counter-objects.

You can make a loop to iterate through the list then return your values
Split and append aren't necessary. When faced with a coding problem, try to find the simplest answer and the most concise without sacrificing any substance.
for words in cars:
cars.count('red', 'blue')
return whatever_you_want

Related

I need to convert the given list of String format to a single list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
need to convert this list :
a = ["['0221', '02194', '02211']"]
type = list
to this list :
a = ['0221', '02194', '02211']
type = list
If your new to python this code would seem like very complicated, but i will explain whats in this piece of code:
a=["['0221', '02194', '02211']"]
a1=[]
nums_str=""
for i in a:
for j in i:
try:
if j=="," or j=="]":
a1.append(nums_str)
nums_str=""
nums=int(j)
nums_str+=str(nums)
except Exception as e:
pass
else:
a=a1.copy()
print(a)
print(type(a))
Steps:
Used for loop to read the content in list a.
Then again used a for loop to read each character in the string of i.
Then used try to try if i can typecast j into int so that it would only add the numbers to nums_str.
Then appended the nums_str to the list a1 if j if = "," or "]".
Continued the above process on each item in a.
After the for loop gets over, i change a to copy of a1.
You can use astliteral_eval to convert strings to Python data structures. In this case, we want to convert the first element in the list a to a list.
import ast
a = ast.literal_eval(a[0])
print(a)
# ['0221', '02194', '02211']
Note: Python built-in function eval also works but it's considered unsafe on arbitray strings. With eval:
a = eval(a[0]) # same desired output
You can try list comprehension:
a = a[0][2:][:-2].split("', '")
output:
a = ['0221', '02194', '02211']

Getting a value from list based on second list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a problem to get the value from first list based on second list. We can assume that we have an election. First list is the list of candidates, second list is the list of votes for this candidates.
candidatesList = [1,2,3,4]
voteList = [2,4,4,1]
One of the rules of election is that, if two or more candidates got same amount of votes then the winner is a candidate with lower number. In this case above output should be 2. I can change data structures but the output must be same.
Simplest way
candidatesList[voteList.index(max(voteList))]
max(voteList) gets you the max of the votes.
voteList.index(max(voteList)) gets you the index of the highest vote from the right hand side.
candidatesList[...] gets you the person
As far as I understand, this might be what you are looking for:
import numpy as np
candidates_list = [1,2,3,4]
vote_list = [2,4,4,1]
best_candidate_index = np.argmax(vote_list)
print("Best candidate", candidates_list[best_candidate_index])
Create dataframe, sort by ['voteList','candidatesList'] and use the top row.
d = dict(candidatesList = [1,2,3,4], voteList = [2,4,4,1])
pd.DataFrame(d).sort_values(by=['voteList','candidatesList'], ascending=[False,True]).candidatesList.iloc[0]

What is the purpose of using {} [()] in the below for loop in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
This for loop runs without any error, but I couldn't figure out what is the purpose of {} [()].
a = [(0, 'Hello'), (1, 'World')]
for {} [()], x in a:
print (x)
The output it produces -
Hello
World
It doesn't have to be a valid name, just a valid assignment target. So it creates a dictionary, {} then assigns 0 (on the first iteration) to the key that is an empty tuple. This is just stupid, there is no purpose. The dicts created are immediately discarded.
So try:
{}[()] = 0
The only real purpose is to take up space in order to throw away the first tuple element, just like _ would.
As to why it's valid python, it translates to:
take an empty dict {}
create a key in it mapped to empty tuple ()
assign the first tuple item in each element in a to it
after the assignment it is gone right away since it is not bound to a name
() can be a dict key because it is hashable, for example:
In [1]: {():1}[()]
Out[1]: 1

create list of increasing number of repeated characters [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to create this kind of output in Python
["k", "kk", "kkk", "kkkk", ...]
["rep", "reprep", "repreprep", ...]
That is a list of n elements, made of the same character (or small group of characters) repeated X times, X being increased by one for each element.
I can't find a way to do this easily, without loops..
Thanks,
Here you have a generator using itertools.count, remember the property of "multiplying" strings in python by a number, where they will be replicated and concatenated nth times, where for example "a"*3 == "aaa" :
import itertools
def genSeq(item):
yield from (item*i for i in itertools.count())
Here you have a live example
repeating_value = "k" #Assign the value which do you want to be repeated
total_times=5 #how many times do you want
expected_list=[repeating_value*i for i in range(1,total_times+1)]
print(expected_list)
character = 'k'
_range = 5
output = [k*x for k in character for x in range(1, _range + 1)]
print(output)
I would multiple my character by a specified number in the range, and then I would simply iterate through the range in a list comprehension. We add 1 to the end of the range in order to get the full range.
Here is your output:
['k', 'kk', 'kkk', 'kkkk', 'kkkkk']
The following is by far the easiest which I have built upon the comment by the user3483203 which eliminates initial empty value.
var = 'rep'
list = [var * i for i in range(1,x,1)]
print(list)

Python names in a list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I'm kinda new to python and was given a problem as follows:
Given the list names , find the largest element in the list and swap it with the last element. For example, the list ["Carlton", "Quincy" "Adam", "Bernard"] would become ["Carlton", "Bernard", "Adam", "Quincy"] . Assume names is not empty
I thought about doing list Comprehension but I don't know how I would write that out in code
EDIT: Largest in this case would be the length of the string (sorry for not clarifying!!!))
names = [foo, fooooo, bar, baaar]
a, b = i.index(max(name, key=len)), -1
i[b], i[a] = i[a], i[b]
Courtesy of this.
If by largest, you mean longest, then you could iterate over the list to find the longest name, and then swap them.
maxLen = 0
maxI = 0
for i in range(0, len(names)):
if len(names[i]) > maxLen:
maxLen = len(names[i])
maxI = i
temp = names[-1]
names[-1] = names[maxI]
names[maxI] = temp
This is an overly convoluted way of doing it, but it's so drawn out to make it more obvious as to what's going on. With that said, you really should be more specific about what "largest" means.

Categories