Python:解析列表的列表

标签 python google-sheets

在 Python 中,我尝试创建一个登录页面,该页面从 Google Sheet 中提取存储的数据以在 Streamlit Authenticator 中使用。 Streamlit Authenticator 通过访问包含用户名、密码和屏幕名称的列表容器来验证登录,如下所示:

username = ['johndoe', 'janedoe']
password = ['123', '456']
names = ['John Doe', 'Jane Doe']

我正在开发的应用程序在云端运行,我将用户数据存储在 Google 表格中,结构如下:

username, password, names
johndoe, 123, John Doe
janedoe, 456, Jane Doe

使用 pysheetsget_as_df 操作,我正在寻求提取数据以填充 Streamlit Authenticator 的容器。但是,当我使用 pysheets 拉取 a 时,各个单元格会作为单独的列表返回,如 username 列的示例所示:

import pygsheets
import pandas as pd

gc = pygsheets.authorize(service_file=local_file) #for Google Sheets API authentication 

sh = gc.open('users') # Google Sheet name
wks = sh0[0] # Worksheet number
database_length = wks0.get_all_values(include_tailing_empty_rows=False, include_tailing_empty=False, returnas='matrix') # for finding the number of filled rows in sheet
end_row = str(len(database_length))
usernames_grab = wks0.get_as_df(has_header=False, index_column=0, start='A2', end=('A'+end_row0), numerize=False) # grabs cell data as dataframe
usernames_list = usernames_grab.values.tolist() # converts dataframe to list
print(usernames_list)

返回结果:

[['johndoe'], ['janedoe']]

然后我尝试相应地设置 Streamlit Authenticator:

username = usernames_list
passwords = password_list
names - names_list

但是在加载脚本时,我收到以下错误: AttributeError: 'list' object has no attribute 'encode' 我猜我无法以这种方式传递列表列表?关于如何继续的任何建议?

最佳答案

这是因为您的用户名是列表的列表,而不是字符串的列表。

您需要做的就是从内部列表中提取字符串。

>>> username = [lst[0] for lst in usernames_list]
['johndoe', 'janedoe']

如果您的 usernames_grab 数据框具有列名称,您也可以这样做:

username = usernames_grab["username"].to_list()

关于Python:解析列表的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71695772/

相关文章:

python - 条件概率计算

python - 需要帮助理解 pytorch 中的梯度函数

python - 获取 DataFrame 当前的分区数

google-apps-script - 脚本属性损坏 : Failed to save Project Properties for script

google-apps-script - 如何将 Google 电子表格与 Google 日历集成?

google-sheets - 如何突出显示两列之间的重复项?

google-apps-script - DriveApp 错误 : "We' re sorry, 发生服务器错误。请稍等,然后再试一次。”

python - Json 将添加的键保留在一起而不创建新的字典

python - 在 Python 3 中写入文件时,TypeError : a bytes-like object is required, 不是 'str'

xpath - 在 Google 工作表中创建函数以获取我的外部 IP 地址