将嵌套的for循环结果存储为单个连接的字符串。

huangapple go评论54阅读模式
英文:

Store results of nested for loop as single concatenated string

问题

I'm sorry, but I can't provide code translation without additional context. If you have any specific questions about the code or need help with a particular part of it, please feel free to ask, and I'll do my best to assist you.

英文:

I'm trying to store the values of the function below to a single string that I can input into a query leveraging an F-string. The output looks correct but is really just a few separated print statements.

How can I store the output of the below to a single string?

import pandas as pd
view_dict = [{'id':'168058','viewtime_min':'2023-01-26 21:00:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'},
                 {'id':'167268','viewtime_min':'2023-01-26 21:59:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'},
                 {'id':'167268','viewtime_min':'2023-01-26 21:59:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'}] 

def get_where_clause(view_dictionary: dict):
    where_clause = " "
    for index in range(len(view_dictionary)): 
        if index != max(range(len(view_dictionary))):
            print(f'''(b.id = {view_dictionary[index]['id']}
                and b.viewed_at between coalesce({view_dictionary[index]['viewtime_min']},published_at) and {view_dictionary[index]['viewtime_max']})
                or''')
        else:
            print(f'''(b.id = {view_dictionary[index]['id']}
                and b.viewed_at between coalesce({view_dictionary[index]['viewtime_min']},published_at) and {view_dictionary[index]['viewtime_max']})''')

x = get_where_clause(view_dict)

x

I'm expecting this to store to a value but when accessing the value nothing is stored.

答案1

得分: 2

你没有实际返回或存储任何东西,print 只是将内容写入控制台。理想情况下,你应该将这些内容收集到类似列表的东西中以便返回,然后可以使用 str.join 连接它们:

view_dict = [{'id':'168058','viewtime_min':'2023-01-26 21:00:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'},
                 {'id':'167268','viewtime_min':'2023-01-26 21:59:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'},
                 {'id':'167268','viewtime_min':'2023-01-26 21:59:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'}] 

def get_where_clause(view_dictionary: dict):
    # 我已经将这个更改为列表
    where_clause = []

    for index in range(len(view_dictionary)): 
        if index != max(range(len(view_dictionary))):
            where_clause.append(f'''(b.id = {view_dictionary[index]['id']}
                and b.viewed_at between coalesce({view_dictionary[index]['viewtime_min']},published_at) and {view_dictionary[index]['viewtime_max']})
                or''')
        else:
            where_clause.append(f'''(b.id = {view_dictionary[index]['id']}
                and b.viewed_at between coalesce({view_dictionary[index]['viewtime_min']},published_at) and {view_dictionary[index]['viewtime_max']})''')
    
    # 在这里连接在一起
    return ' '.join(where_clause)

x = get_where_clause(view_dict)

print(x)

我知道这不是要求的,但是这可以通过一些基本的迭代技巧进一步简化:

def get_where_clause(view_dictionary: list):
    # 我已经将这个更改为列表
    where_clause = []

    # 获取最后一个元素并在切片上迭代,而不是检查索引
    last = view_dictionary[-1]

    # 直接迭代视图,不使用索引
    for item in view_dictionary[:-1]:
        where_clause.append(f'''(b.id = {item['id']}
                and b.viewed_at between coalesce({item['viewtime_min']},published_at) and {item['viewtime_max']})
                or''')
    
     where_clause.append(f'''(b.id = {last['id']}
                and b.viewed_at between coalesce({last['viewtime_min']},published_at) and {last['viewtime_max']})''')
    
    # 在这里连接在一起
    return ' '.join(where_clause)

为了简化格式,你可以使用括号来缩进单个字符串:

    for item in view_dictionary:
        where_clause.append(
            f"(b.id = {item['id']} "
            "and b.viewed_at between "
            f"coalesce({item['viewtime_min']},published_at) "
            f"and {item['viewtime_max']})"
        )
    
    # 而不是检查第一个/最后一个,你可以连接 'or' 
    return ' or '.join(where_clause)
英文:

You aren't actually returning or storing anything, print simply writes to the console. Ideally, you'd collect these into something like a list to be returned, which you can then use str.join to concatenate:

view_dict = [{'id':'168058','viewtime_min':'2023-01-26 21:00:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'},
                 {'id':'167268','viewtime_min':'2023-01-26 21:59:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'},
                 {'id':'167268','viewtime_min':'2023-01-26 21:59:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'}] 

def get_where_clause(view_dictionary: dict):
    # I've changed this to a list
    where_clause = []

    for index in range(len(view_dictionary)): 
        if index != max(range(len(view_dictionary))):
            where_clause.append(f'''(b.id = {view_dictionary[index]['id']}
                and b.viewed_at between coalesce({view_dictionary[index]['viewtime_min']},published_at) and {view_dictionary[index]['viewtime_max']})
                or''')
        else:
            where_clause.append(f'''(b.id = {view_dictionary[index]['id']}
                and b.viewed_at between coalesce({view_dictionary[index]['viewtime_min']},published_at) and {view_dictionary[index]['viewtime_max']})''')
    
    # join together here
    return ' '.join(where_clause)



x = get_where_clause(view_dict)

print(x)

I know it isn't asked for, but this could be cleaned up a little more with some basic iteration techniques:

def get_where_clause(view_dictionary: list):
    # I've changed this to a list
    where_clause = []

    # grab the last element and iterate over a slice
    # rather than checking an index
    last = view_dictionary[-1]

    # iterate over the views directly, don't use an index
    for item in view_dictionary[:-1]:
        where_clause.append(f'''(b.id = {item['id']}
                and b.viewed_at between coalesce({item['viewtime_min']},published_at) and {item['viewtime_max']})
                or''')
    
     where_clause.append(f'''(b.id = {last['id']}
                and b.viewed_at between coalesce({last['viewtime_min']},published_at) and {last['viewtime_max']})''')
    
    # join together here
    return ' '.join(where_clause)

And to simplify formatting, you can indent a single string by using parentheses:

    for item in view_dictionary:
        where_clause.append(
            f"(b.id = {item['id']} "
            "and b.viewed_at between "
            f"coalesce({item['viewtime_min']},published_at) "
            f"and {item['viewtime_max']})"
        )
    
    # rather than checking for first/last, you can join on
    # 'or' 
    return ' or '.join(where_clause)

</details>



# 答案2
**得分**: 1

以下是代码部分的翻译

```py
The `print` command just writes the text to your screen, it does not return a value. Your function needs to return a value for it to be "storable" in a variable.

I rewrote, formatted and commented your code, it now returns a string containing the where clause:

view_dict = [
    {
        "id": "168058",
        "viewtime_min": "2023-01-26 21:00:59.435 -0600",
        "viewtime_max": "2023-01-26 21:59:59.435 -0600",
    },
    {
        "id": "167268",
        "viewtime_min": "2023-01-26 21:59:59.435 -0600",
        "viewtime_max": "2023-01-26 21:59:59.435 -0600",
    },
    {
        "id": "167268",
        "viewtime_min": "2023-01-26 21:59:59.435 -0600",
        "viewtime_max": "2023-01-26 21:59:59.435 -0600",
    },
]

def get_where_clause(view_dictionary: list[dict]) -> str:
    # 这是所有输出将存储的地方
    outputs = []
    # 遍历view_dictionary,实际上是一个字典列表
    for vd in view_dictionary:
        # 为了提高可读性:从每个字典中获取相关部分
        bid = vd['id']
        tmin = vd['viewtime_min']
        tmax = vd['viewtime_max']
        # 将所有内容放入f-string中
        output = f"(b.id = {bid} and b.viewed_at between coalesce('{tmin}', published_at) and '{tmax}') or"
        # 仅供娱乐,您不会使用此输出
        print(output)
        # 将每个输出放入outputs列表中
        outputs.append(output)
    # 通过将所有输出连接成一个字符串来创建实际的WHERE子句
    # [:-3] 确保最后的 'or' 关键字被移除
    where_clause = " ".join(outputs)[:-3]
    return where_clause

x = get_where_clause(view_dict)
英文:

The print command just writes the text to your screen, it does not return a value. Your function needs to return a value for it to be "storable" in a variable.

I rewrote, formatted and commented your code, it now returns a string containing the where clause:

view_dict = [
    {
        &quot;id&quot;: &quot;168058&quot;,
        &quot;viewtime_min&quot;: &quot;2023-01-26 21:00:59.435 -0600&quot;,
        &quot;viewtime_max&quot;: &quot;2023-01-26 21:59:59.435 -0600&quot;,
    },
    {
        &quot;id&quot;: &quot;167268&quot;,
        &quot;viewtime_min&quot;: &quot;2023-01-26 21:59:59.435 -0600&quot;,
        &quot;viewtime_max&quot;: &quot;2023-01-26 21:59:59.435 -0600&quot;,
    },
    {
        &quot;id&quot;: &quot;167268&quot;,
        &quot;viewtime_min&quot;: &quot;2023-01-26 21:59:59.435 -0600&quot;,
        &quot;viewtime_max&quot;: &quot;2023-01-26 21:59:59.435 -0600&quot;,
    },
]


def get_where_clause(view_dictionary: list[dict]) -&gt; str:
    # This is where all the outputs will be stored
    outputs = []
    # Loop over the view_dictionary, which is actually a list of dicts
    for vd in view_dictionary:
        # Just for readability: get the relevant parts out of each dict
        bid = vd[&#39;id&#39;]
        tmin = vd[&#39;viewtime_min&#39;]
        tmax = vd[&#39;viewtime_max&#39;]
        # Place everything in an f-string
        output = f&quot;(b.id = {bid} and b.viewed_at between coalesce(&#39;{tmin}&#39;,published_at) and &#39;{tmax}&#39;) or&quot;
        # Print, just for fun, you won&#39;t use this output
        print(output)
        # Place every output in the outputs list
        outputs.append(output)
    # Create the actual WHERE clause by concatenating all outputs into a single string
    # the [:-3] makes sure the last &#39;or&#39; keyword is removed
    where_clause = &quot; &quot;.join(outputs)[:-3]
    return where_clause


x = get_where_clause(view_dict)

huangapple
  • 本文由 发表于 2023年2月7日 04:34:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366295.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定