来自两本词典:
d1 = {a:a for a in 'abcdefg'}
d2 = {n:n for n in range(10)}
Run Code Online (Sandbox Code Playgroud)
我怎样才能创建第三个,例如:
new_dict = {k:d1[k] if k in d1.keys() else k:d2[k] for k in 'abc123' }
Run Code Online (Sandbox Code Playgroud)
它抛出语法错误,但使用列表理解似乎没问题:
[a if a else 2 for a in [0,1,0,3]]
out[]: [2, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
此外,为什么这有效:
{k:d1[k] for k in 'abc123' if k in d1.keys() }
Run Code Online (Sandbox Code Playgroud)
这不是:
{k:d1[k] if k in d1.keys() for k in 'abc123' }
Run Code Online (Sandbox Code Playgroud) 我有一个名单:
a = ['Maria','Luis','Andrea']
Run Code Online (Sandbox Code Playgroud)
我想把它们放在一个字符串中,所以我这样做:
names = ''
for name in a:
names = names +',' ' ' + name
Run Code Online (Sandbox Code Playgroud)
有一个问题,在第一次迭代中我在开头添加一个逗号和一个空格,我知道我可以删除逗号和空格但我宁愿只是没有它.
此外,这可以在lambda函数中完成吗?
我有一个数据框,其中包含产品列表及其各自的评论
+ --------- + --------------------------------------- --------- +
| 产品| 审查|
+ --------- + --------------------------------------- --------- +
| product_a | 这适合休闲午餐
+ --------- + --------------------------------------- --------- +
| product_b | 艾弗里是最知识渊博的咖啡师之一
+ --------- + --------------------------------------- --------- +
| product_c | 导游告诉我们秘密|
+ --------- + --------------------------------------- --------- +
如何获取数据框中的所有唯一单词?
我做了一个功能:
def count_words(text):
try:
text = text.lower()
words = text.split()
count_words = Counter(words)
except Exception, AttributeError:
count_words = {'':0}
return count_words
Run Code Online (Sandbox Code Playgroud)
并将该函数应用于DataFrame,但这只给了我每行的单词计数.
reviews['words_count'] = reviews['review'].apply(count_words)
Run Code Online (Sandbox Code Playgroud) 我正在使用 streamlit 制作一个基本的可视化应用程序来比较两个数据集,为此我使用了 Marc Skov 从 streamlit 画廊制作的以下示例:
from typing import Dict
import streamlit as st
@st.cache(allow_output_mutation=True)
def get_static_store() -> Dict:
"""This dictionary is initialized once and can be used to store the files uploaded"""
return {}
def main():
"""Run this function to run the app"""
static_store = get_static_store()
st.info(__doc__)
result = st.file_uploader("Upload", type="py")
if result:
# Process you file here
value = result.getvalue()
# And add it to the static_store if not already in
if not value in static_store.values(): …Run Code Online (Sandbox Code Playgroud)