私信  •  关注

Charles Landau

Charles Landau 最近创建的主题
Charles Landau 最近回复了
6 年前
回复了 Charles Landau 创建的主题 » 在Python3.x中查找数组是否存在且不为空

在你的代码片段中 p2 是一个字符串( json.dumps 皈依者 y 到字符串中的有效json对象)

isinstance 是检查的首选方式,因此您可以使用:

if isinstance(y['attributes'], list):
    len(y['attributes'])
6 年前
回复了 Charles Landau 创建的主题 » 使用python在文件中写入数据

让我们来回顾一下:

name = input("Your name: ")
email = input("Your email: ")

正如已经指出的那样,结束语是必要的。

outputString = name + "|" + email + "|" +  favoriteband 

outputString 遗失了一个 + 之前 email

最后,我们需要重写您的文件管理:

with open(fileName, "a") as file:
  file.write (outputString) 
  print (outputString , " saved in ", fileName) 

作为一个 with 声明保证它会关闭。使用 open(..., "a") 以“追加”模式打开文件,并允许您将多个字符串写入同一名称的文件。

最后,如果我能做到这一点,到目前为止我还不是这本书的爱好者。

编辑:这是全部的代码和修复,希望能让你到那里。

name = input("name")
email = input("whats ure email:") 
favoriteband = input("ure fav band") 
outputString = name + "|" + email + "|" +  favoriteband 
fileName = name + ".txt"
with open(fileName, "a") as file:
  file.write (outputString) 
  print (outputString , " saved in ", fileName) 

您可以验证它的工作原理:

with open(fileName, "r") as file:
  print(file.read())
6 年前
回复了 Charles Landau 创建的主题 » 如何在python中输入嵌套列表?

对于几乎所有有效的python,我认为最简单的答案是

your_variable_name = your_python_object
# So with nested list:
your_variable_name = your_nested_list

在函数中,您可以像任何其他输入那样做它:

def nested_list_getter(nested_list):
    # ... your processing of the list here
6 年前
回复了 Charles Landau 创建的主题 » python list:append vs+=[重复]

这是一个 __iadd__ 操作员。 Docs.

重要的是,这意味着 尝试 追加。”例如,如果x是具有 __iadd__() 方法, x += y 相当于 x = x.__iadd__(y) . 否则, x.__add__(y) y.__radd__(x) 在评估 x + y

This thread specifically deals with lists and their iadd behavior

6 年前
回复了 Charles Landau 创建的主题 » 如何使用python删除重复的文本块

在python中,纯文本文件可以表示为序列。考虑 plain.txt 以下:

This is the first line!\n
This is the second line!\n
This is the third line!\n

你可以使用 with 保留字以创建管理打开/关闭逻辑的上下文,如下所示:

with open("./plain.txt", "r") as file:
    for line in file:
        # program logic
        pass

"r" 指open使用的模式。

因此,使用这个习惯用法,您可以以适合您的文件访问模式的方式存储重复值,并在遇到重复值时忽略它。

编辑:我看到你的编辑,看起来这实际上是一个csv,对吧?如果是的话,我推荐熊猫套餐。

import pandas as pd # Conventional namespace is pd

# Check out blob, os.walk, os.path for programmatic ways to generate this array
files = ["file.csv", "names.csv", "here.csv"] 

df = pd.DataFrame()
for filepath in files:
    df = df.append(pd.read_csv(filepath))

# To display result
print(df)

# To save to new csv
df.to_csv("big.csv")