我正在抓取多个网站,所以我为每个网站脚本使用一个函数,因此每个函数都返回4个值,我想在dataframe中打印它们并将它们写入csv,但是我遇到了这个问题,我可能会问一些问题太奇怪或太基本了,但请帮助
要么我要么必须在一个块中编写整个脚本,而且处理起来似乎很讨厌,所以如果我能找到解决方法,这只是我所面临的问题的一个示例。
def a1(x):
z=x+1
r = x+2
print(z, r)
def a2(x):
y=x+4
t=x+3
print(y, t)
x = 2
a1(x)
a2(x)
3 4
6 5
data = pd.Dataframe({'first' : [z],
'second' : [r],
'third' : [y],
'fourth' : [t]
})`
data
*error 'z' is not defined*
答案 0 :(得分:0)
仅在函数的局部范围内定义变量,您要么需要全局声明它们,要么(更好的方法是)返回它们,以便您可以通过将返回值分配给新变量来在函数外部使用它们
gradle
答案 1 :(得分:0)
您可能会发现编写返回字典列表的函数很方便。
例如:
import React from 'react';
import { connect } from 'react-redux';
import orderBy from '../actions/sorting';
const TYPES = [
{ slug: "title", description: "Title" },
{ slug: "author", description: "Author" },
{ slug: "editionYear", description: "Edition Year" }
];
class BookListSorter extends React.Component {
state = {
sortBy: [{ title: "asc" }]
};
// Helper methods
getSortByKeyForIndex = index =>
Object.keys(this.state.sortBy[index] || {})[0];
getSortByValueForIndex = index =>
Object.values(this.state.sortBy[index] || {})[0];
changeSort = (key, index) => e => {
// This is what is called when an select option changes
const { target } = e; // Save target from event to use in the callback
this.setState(({ sortBy }) => {
// Use a function for atomicness - this prevents state from being out of sync
// Get the type from the event object if the onchange handler is for the type,
// otherwise get from sortBy object
const type =
key === "type" ? target.value : this.getSortByKeyForIndex(index);
// Get the direction from the event object if the onchange handler is for the direction,
// otherwise get from sortBy object
const direction =
key === "direction" ? target.value : this.getSortByValueForIndex(index);
// If both options are set, replace the indexed spot in the sortby object
// Return updated state.
return type || direction
? sortBy.splice(index, 1, { [type]: direction })
: sortBy.splice(index, 1);
});
};
filterTypes = index => ({ slug }) => {
// Filter out already used keys from previous rows
const sortByKeys = this.state.sortBy
.slice(0, index)
.reduce((keys, sortObj) => keys.concat(Object.keys(sortObj)[0]), []);
return !sortByKeys.includes(slug);
};
render() {
const { sortBy } = this.state;
const lastIndex = sortBy.length - 1;
// Only add a new row if the one above it is completely filled out
const shouldAddNewRow =
this.getSortByKeyForIndex(lastIndex) &&
this.getSortByValueForIndex(lastIndex);
const rowCount = shouldAddNewRow ? sortBy.length + 1 : sortBy.length;
return (
<div>
<h1>Choose sort order</h1>
{Array.from(Array(Math.min(rowCount, TYPES.length))).map(
(dummy, index) => (
<div>
<span>Row {index}: </span>
<select
defaultValue={this.getSortByKeyForIndex(index)}
onChange={this.changeSort("type", index)}
>
<option value="">None</option>
{TYPES.filter(this.filterTypes(index)).map(
({ slug, description }) => (
<option value={slug}>{description}</option>
)
)}
</select>
<select
defaultValue={this.getSortByValueForIndex(index)}
onChange={this.changeSort("direction", index)}
>
<option value="">None</option>
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>
<br />
</div>
)
)}
<br />
<button onClick={() => this.props.dispatch(orderBy(sortBy))}>sort</button>
</div>
);
}
};
const mapStateToProps = (state) => {
return {
sorting: state.sorting
};
};
//ACTIONS
//ADD BOOK
const addBook = ({ title = '', author = '', editionYear = 0} = {}) => ({
type: 'ADD_BOOK',
book: {
title,
author,
editionYear
}
});
//SORT BY
const orderBy = (order) => ({
type: 'SORT_BY',
orderBy: order
});
//book reducer
const bookReducerDefaultState = [];
const bookReducer = (state = bookReducerDefaultState, action) => {
switch(action.type) {
case 'ADD_BOOK':
return [
...state,
action.book
];
default:
return state;
};
};
//sorting reducer
const sortingReducerDefaultState = {
orderBy: [{title: 'asc'},{author: 'asc'}]
};
const sortingReducer = (state = sortingReducerDefaultState, action) => {
switch(action.type) {
case 'SORT_BY':
return {
...state,
orderBy: action.orderBy
};
default:
return state;
};
}
function compareBy(a, b, orderBy) {
const key = Object.keys(orderBy)[0],
o = orderBy[key],
valueA = a[key],
valueB = b[key];
if (!(valueA || valueB)) {
console.error("the objects from the data passed does not have the key '" + key + "' passed on sort!");
return 0;
}
if (+valueA === +valueA) {
return o.toLowerCase() === 'desc' ? valueB - valueA : valueA - valueB;
} else {
if (valueA.localeCompare(valueB) > 0) {
return o.toLowerCase() === 'desc' ? -1 : 1;
} else if (valueA.localeCompare(valueB) < 0) {
return o.toLowerCase() === 'desc' ? 1 : -1;
}
}
return 0
}
function getSortedBooks(books, orderBy) {
orderBy = Array.isArray(orderBy) ? orderBy : [orderBy];
return books.sort((a, b) => {
let result
for (let i = 0; i < orderBy.length; i++) {
result = compareBy(a, b, orderBy[i])
if (result !== 0) {
return result
}
}
return result
})
}
//store creation
const store = createStore(
combineReducers({
books: bookReducer,
sorting: sortingReducer
})
);
store.subscribe(() => {
const state = store.getState();
const sortedBooks = getSortedBooks(state.books, state.sorting.orderBy)
console.log(sortedBooks);
});
export default connect(mapStateToProps)(BookListSorter);