How to call a string from a list in python

I'm struggling with how to correctly feed a list of strings one-by-one into a pre-defined function. The list looks like this:

riclist = ["XAU=", "XAG=", "XPT=", "XPD="]

And the function looks like this [note that ek.get_timeseries is a pre-defined function from the Eikon library, but this problem could be generalized to any similar one]:

def get_variable[input]:

    chosenric = riclist[ ##each item one-by-one## ]

    var = ek.get_timeseries[rics=chosenric, 
                            start_date=2018-01-01,
                            fields="CLOSE"] 

    return[var]

And the end result I'm after is a DataFrame with the time-series for all n variables in riclist.

asked Aug 9, 2018 at 11:11

5

How about:

for item in riclist:
    var = ek.get_timeseries[rics=chosenric, 
                        start_date=2018-01-01,
                        fields="CLOSE"]
    ....do the rest here for each item

answered Aug 9, 2018 at 11:16

questquest

3,1431 gold badge13 silver badges23 bronze badges

1

I may be missing something in the question, but if the question is:

How to run a function on a list of arguments then there are a few simple ways:

  1. results = [get_variable[input] for input in riclist]
  2. results = map[get_variable, riclist]

answered Aug 9, 2018 at 11:18

Not sure if I completely understand your question, but are you looking for a for loop?

for ric in riclist:
    var = ek.get_timeseries[rics=ric, 
                            start_date=2018-01-01,
                            fields="CLOSE"] 

then, if you want to return one at a time, you could use a generator

    yield var

answered Aug 9, 2018 at 11:19

1

Returns a dict-like {chosenric : timeseries}

def get_variable[riclist]:
    return {chosenric : ek.get_timeseries[rics=chosenric, start_date=2018-01-01, fields="CLOSE"] for chosenric in riclist}

answered Aug 9, 2018 at 11:20

7

It is probably better to ask these kind of questions on the Thomson Reuters Developer Portal, because you are asking something [licensed] product specific, which is not useful for the StackOverflow community.

That being said, the get_timeseries function can be fed a list of instruments directly. It always returns a pandas dataframe. So you probably want to do this:

df = ek.get_timeseries[riclist, fields="CLOSE", start_date='2018-01-01']

If you really need it to be part of a function, you could do this:

def get_variable[]:

    var = ek.get_timeseries[rics=riclist, 
                            start_date="2018-01-01",
                            fields="CLOSE"] 

    return[var]

Please check out the documentation

**Disclaimer: I am currently employed by Thomson Reuters

answered Aug 16, 2018 at 13:15

PythonSherpaPythonSherpa

2,4202 gold badges16 silver badges39 bronze badges

In this article, we’ll take a look at how we can find a string in a list in Python.

There are various approaches to this problem, from the ease of use to efficiency.

Using the ‘in’ operator

We can use Python’s in operator to find a string in a list in Python. This takes in two operands a and b, and is of the form:

Here, ret_value is a boolean, which evaluates to True if a lies inside b, and False otherwise.

We can directly use this operator in the following way:

a = [1, 2, 3]

b = 4

if b in a:
    print['4 is present!']
else:
    print['4 is not present']

Output

We can also convert this into a function, for ease of use.

def check_if_exists[x, ls]:
    if x in ls:
        print[str[x] + ' is inside the list']
    else:
        print[str[x] + ' is not present in the list']


ls = [1, 2, 3, 4, 'Hello', 'from', 'AskPython']

check_if_exists[2, ls]
check_if_exists['Hello', ls]
check_if_exists['Hi', ls]

Output

2 is inside the list
Hello is inside the list
Hi is not present in the list

This is the most commonly used, and recommended way to search for a string in a list. But, for illustration, we’ll show you other methods as well.

Using List Comprehension

Let’s take another case, where you wish to only check if the string is a part of another word on the list and return all such words where your word is a sub-string of the list item.

Consider the list below:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

If you want to search for the substring Hello in all elements of the list, we can use list comprehensions in the following format:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

matches = [match for match in ls if "Hello" in match]

print[matches]

This is equivalent to the below code, which simply has two loops and checks for the condition.

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

matches = []

for match in ls:
    if "Hello" in match:
        matches.append[match]

print[matches]

In both cases, the output will be:

['Hello from AskPython', 'Hello', 'Hello boy!']

As you can observe, in the output, all the matches contain the string Hello as a part of the string. Simple, isn’t it?

Using the ‘any[]’ method

In case you want to check for the existence of the input string in any item of the list, We can use the any[] method to check if this holds.

For example, if you wish to test whether ‘AskPython’ is a part of any of the items of the list, we can do the following:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

if any["AskPython" in word for word in ls]:
    print['\'AskPython\' is there inside the list!']
else:
    print['\'AskPython\' is not there inside the list']

Output

'AskPython' is there inside the list!

Using filter and lambdas

We can also use the filter[] method on a lambda function, which is a simple function that is only defined on that particular line. Think of lambda as a mini function, that cannot be reused after the call.

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

# The second parameter is the input iterable
# The filter[] applies the lambda to the iterable
# and only returns all matches where the lambda evaluates
# to true
filter_object = filter[lambda a: 'AskPython' in a, ls]

# Convert the filter object to list
print[list[filter_object]]

Output

We do have what we expected! Only one string matched with our filter function, and that’s indeed what we get!

Conclusion

In this article, we learned about how we can find a string with an input list with different approaches. Hope this helped you with your problem!

References

  • JournalDev article on finding a string in a List
  • StackOverflow question on finding a string inside a List

How do you get a string from a list Python?

To convert a list to a string, use Python List Comprehension and the join[] function. The list comprehension will traverse the elements one by one, and the join[] method will concatenate the list's elements into a new string and return it as output.

How do I find a string in a list?

Python Find String in List using count[] We can also use count[] function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.

How do you define a string in a list Python?

To create a list of strings, first use square brackets [ and ] to create a list. Then place the list items inside the brackets separated by commas. Remember that strings must be surrounded by quotes. Also remember to use = to store the list in a variable.

How do I extract a specific word from a list in Python?

The list is iterated over, and every element is split based on spaces. The 'iskeyword' method is used to check if any of the elements in the list are a keyword in the language. If yes, it is appended to the empty list.

Chủ Đề