python - 根据字符串长度填充列表的空列表

标签 python string list

假设我有以下单词列表

words = ["arid", "dash", "drain", "thread"]

和一个空的列表列表:

a=[[]]*7

我想将这些单词放入列表列表中,以便每个单词的长度决定它们附加到的列表的位置。

例如,因为“rid”的长度为 4,所以它会继续:

a=[[],[],[],[],["arid"],[],[]]

“dash”的长度也是 4,所以它会继续:

a=[[],[],[],[],["arid", "dash"],[],[]]

但是“drain”的长度为 5,所以它会继续:

a=[[],[],[],[],["arid", "dash"],["brain"],[]]

并且“thread”的长度为 6,所以它会继续:

a=[[],[],[],[],["arid", "dash"],["brain"],["thread"]]

我尝试了以下代码:

A = [[]]*7 #7 is len(thread)+1. it's not hard coded in my implementation

for word in words:
    size=len(word)
    A[size].append(word)
print(A)

当我运行这个时,我得到:

>>[['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread'], ['arid', 'dash', 'drain', 'thread']]

这毫无意义。每次我附加时,该单词都会附加到列表列表中的每个列表中。我究竟做错了什么?有人可以帮忙吗?

最佳答案

您需要更改为A = [[]for _ in range(7)]。您可以尝试如下:

A = [[]for _ in range(7)] #7 is len(thread)+1. it's not hard coded in my implementation

for word in words:
    size=len(word)
    A[size].append(word)
print(A)

输出:

[[], [], [], [], ['arid', 'dash'], ['drain'], ['thread']]

关于python - 根据字符串长度填充列表的空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52452817/

相关文章:

python - pickle ,numpy - reshape 参数?

python - 在 Python/Seaborn 的图例中显示置信区间

python - 在 Python 中将反斜杠作为命令行参数处理

C:将元素从一个列表移动到另一个列表

python - 如何处理 Pytjon 列表列表中具有二进制值的样本的索引超出范围和无效语法?

c# - 如何将 List<string> 绑定(bind)到 WebForms 中的 ListView

python - 使用 Python Asyncore 构建 SNMP 请求-响应服务

python - 在间隔列表上自定义 pandas groupby

java - 检索两个字符之间的字符串

java - String.format/Formatter 中的错误?