Python: insert 68 empty strings into a list [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I am extracting values from excel into a list but some of them are blank.
I want to check if the list is empty, and if empty insert 68 empty strings. Is there a way to do that?
a = []
if not a:
#enter 68 empty strings into a. eg: a = ['', '', '',....]

Python lets you multiply a list with a number to repeat it:
a = [''] * 68
If you also have other references to this list, so you actually need to update the same list instead of creating an new one, use extend:
a.extend([''] * 68)

Using the logical or operator, you can avoid conditions to create the list with empty strings, or keep the original list in case it was not empty:
a = a or [''] * 68
If a is empty, then it's falsey so the or will return the second argument.
If a is not empty, it is truthy so the or will return it.

a = []
if not a:
a.extend(["" for _ in range(68)])

Suppose you have a list a, and we want to insert n=68 blank strings at position i
a = [1, 2]
i = 1
n = 68
result = a[:i] + [''] * n + a[i:]
Then of course you can set a = result if you wanted to modify a directly. This is of course overkill, as you don't really want to insert into an existing list, this time, but I thought I'd answer the question asked.

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']

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)

Separating strings in CamelCase to individual strings [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 5 years ago.
Improve this question
The question is as follows:
"A string exists in CamelCase format. For example: "ThisIsACamelCaseString".
A procedure/function is required that will:
1) prompt for the original entry
2) separate each word of the string
3) store each word in a separate array/list element
4) fill unused array/list elements with a rogue string such as "(Empty)".
After processing the preceding example, the array contents will look like this:
This
Is
A
Camel
Case
String
(Empty)
(Empty)
(Empty)
(Empty)
You may assume that the original string will contain no more than 10 separate words. Write program code in Python for this design."
This is what I tried:
a = input("Enter: ")
lists = list(a)
len = len(a)
alpha = ["Empty"]*10
alpha[0] = lists[0]
for i in range(len):
for j in range(len):
if lists[j + 1].isupper():
break
alpha[i] = alpha[i] + lists[j + 1]
for i in range(10):
print(alpha[i])
How do I find suitable code?
This is one way to do it:
a = 'ThisIsACamelCaseString'
b = [i for i, e in enumerate(a) if e.isupper()] + [len(a)]
c = [a[x: y] for x, y in zip(b, b[1:])]
final = ['(Empty)']*10
for i, case in enumerate(c):
final[i] = case
Use regular expressions to split camel case How to do CamelCase split in python .
Or just iterate over the string in a loop.

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.

element that appear more that once in the list in Python [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 4 years ago.
Improve this question
Please help (I know that it's a silly question):
I have a list d = [' ABA', ' AAB', ' BAA', ' BAA', ' AAB', ' ABA']. How can I exclude elements that appear more than once?
To exclude items from the list that appear more than once:
d = [x for x in d if d.count(x) == 1]
For the example provided above, d will bind to an empty list.
Others have posted good solutions to remove duplicates.
Convert to a set then back again:
list(set(d))
If order matters, you can pass the values through a dict that remembers the original indices. This approach, while expressible as a single expression, is considerably more complicated:
[x for (i, x) in sorted((i, x) for (x, i) in dict((x, i) for (i, x) in reversed(list(enumerate(d)))).iteritems())]
Of course, you don't have to use comprehensions. For this problem, a fairly simple solution is available:
a = []
for x in d:
if x not in a:
a.append(x)
Note that both the order-preserving solutions assume that you want to keep the first occurrence of each duplicated element.
Lets say you got a list named Words and a list UniqueWords, start a loop on Words, on each iteration you check if the list UniqueWords contains the iterated element, if so then continue, if not then add it to the UniqueWords. In the end you will have a list without duplicates. Another way you could do is a loop in a loop and instead of adding you'd remove it if it was found more than once :)
I bet there are far more efficient ways though.
If you're not worried about the order, d = list(set(d))).
If order matters check out the unique_everseen function in the itertools recpies documentation. It give a relatively clean iterator-based solution.
If order doesn't matter, convert to a set.
If you shouldn't have done that already, make sure to read the python docs on itertools, especially product(), permutations() and combinations().

Categories